Reputation: 192
public class B {
public B() {
}
private void m0(){
System.out.println("BO");
}
public void m1(){
System.out.println("B1");
}
public void test(){
this.m0();
this.m1();
}
}
public class D extends B{
/**
*
*/
public D() {
}
public void m0(){
System.out.println("DO");
}
public void m1(){
System.out.println("D1");
}
public void test(){
super.test();
}
public static void main(String[] args) {
B d=new D();
d.test();
}
}
My question is why the output is BO,D1
instead of BO,B1
. I am not getting how the super
keyword plays the role of calling the methods of the child class instead of the parent class.
Upvotes: 5
Views: 130
Reputation: 1599
The method m0 is private in class B. So when inheriting, m0 method is private and is not inherited in class D. So, method m0 of class B is executed and "BO" is printed.
But when this.m1() is executed, it is overridden by the method m1 in class D. So it prints "D1"
Upvotes: 0
Reputation: 7476
So the super keyword ensure that the version of the test function that is called is from the super class (specifically B.test() as opposed to recusively calling D.test()).
But that doesn't answer your question exactly.
The reason the second term is D1 not B0, because the D.m1() polymorphically overrides the B.m1().
The reason the first term is B0 not D0, because the D.m0() does NOT override the B.m0() because b.m0 is private.
Upvotes: 1
Reputation: 5463
Because your method m0
in class B is private, it is not overridden by class D.
Upvotes: 8