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

前端 未结 4 920
长情又很酷
长情又很酷 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:27

    I guess this is not considered a case of method overriding because the signatures are not exactly the same. Change the String argument to Object in B.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-20 06:41

    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 were to use a reference of type B, both methods would be available, and doSomething of B would be chosen, since it has a more specific argument (String vs Object).

    0 讨论(0)
  • 2021-01-20 06:41

    In class A, you have declared a method doSomething(Object obj). However, in class B, you have declared the method doSomething(String str), which has a different parameter type than the one in class A. This means that class B's doSomething doesn't override class A's doSomething.

    To get the desired output, do the following (I omitted the main methods to get a more generic code sample):

    public class A {
        public void doSomething(Object str){
            System.out.println("Base impl:"+str);
        }
    }
    
    public class B extends A {
        // Helpful annotation: It tells you
        // if you aren't overriding any known method
        @Override
        public void doSomething(Object str) {
            System.out.println("Child impl:"+str);
        }
    }
    
    0 讨论(0)
提交回复
热议问题