Why parent class method is getting called and not child class in this case?

前端 未结 4 919
长情又很酷
长情又很酷 2021-01-20 06:16

I have a parent class A, and its child B. Both are having doSomething method with diff type of parameters.

Class A

package Inheritance;
         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 06:28

    As @Eran said

    When you are using a reference of type A, you see only the methods defined for class A. Since doSomething in B doesn't override doSomething in A (since it has a different signature), it is not called.

    if you wanna call the method defined in B you need to cast it as following

    ((B)a).doSomething("override");
    

    or you have to used the instance of B implicitly

提交回复
热议问题