I have a parent class A, and its child B. Both are having doSomething
method with diff type of parameters.
Class A
package Inheritance;
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.
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
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).
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);
}
}