How to call an non overide method of child class using parent object reference

后端 未结 3 1728
生来不讨喜
生来不讨喜 2021-01-27 10:28

Here is my code want to access child class method of AdapterVer1 getAdaptObj1() (without type casting) using object reference of AdapterVersion (Parent class)

ab         


        
3条回答
  •  独厮守ぢ
    2021-01-27 11:15

    You can't do that. Because at compile time, the compiler checks whether the method you invoked is accessible or visible in the class of the reference you are using or not.

    So, in this case, since the reference is of Parent class, the compiler will look for the method declaration in the Parent class first in order to successfully compile the code.

    Remember: -

    Compiler is worried about the Reference type, and at runtime, the actual object type is considered, to decide which method to actually invoke.

    The only option you have is to typecast, in which case, the compiler now looks into the class in which you typecasted the reference. Other option is, you can declare an abstract method with that name in Parent class, but from your question, it seems like you explicitly haven't done that.

提交回复
热议问题