abstract class A {
public void methodA() {
System.out.println("methodA");
methodB();
showName();
}
public abstract void methodB();
public void showName() {
System.out.println("in showname base");
}
}
class B extends A {
public void methodB() {
System.out.println("methodB");
}
public void showName() {
System.out.println("in showname child");
}
}
public class SampleClass {
public static void main(String[] args) {
A a = new B();
a.methodA();
}
}
Output is :
methodA
methodB
in showname child
Question :-
Since in overriding, the object type is considered. Is it the reason behind that class B’s showName() method called not of class A’s? If not then whats the cause of this output order?
It’s easy:
here is known that a is object of
Bclass, so every method that can be overriden in classBis used from classBif there is no overriding, then method from classAmust be used.Considering order:
you invoke
methodAthat is declared as:from inside of
methodA()you invoke bothmethodB()andshowName(). They are overriden in classB, and object a isinstanceof B, so that’s why they (from B class) are used.EDIT as mentioned in comment:
@Jaikrat Singh, class B is still class A (child of it, but inheritance is relation of type: IS-A ). Class
Bhas inherited methods fromAclass. So it hasmethodAas well. So it’s better to say, thatmethodAis also called from classBbut with is default code – the same as provided in classA