How the super keyword works in java-Java Puzzle

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 do not understand how the super keyword plays the role of calling methods of a child class instead of the parent class.

+5
source share
3 answers

Since your method m0 in class B is private, it is not overridden by class D.

+8
source

Thus, the super keyword ensures that the version of the called function will be called by the super class (in particular, B.test (), and not by D.test ()).

But this certainly does not answer your question.

The reason the second term D1 is not B0, because D.m1 () polymorphically redefines B.m1 ().

The reason the first member of B0 is not D0 is because D.m0 () DOES NOT override B.m0 () because b.m0 is private.

+1
source

The m0 method is private in class B. Therefore, when inheriting, the m0 method is private and not inherited in class D. So, the m0 method of class B is executed and "BO" is printed.

But when this .m1 () is executed, it is overridden by the m1 method in class D. Thus, it prints "D1"

0
source

All Articles