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.
The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.
super() acts as immediate parent class constructor and should be first line in child class constructor. this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.
Difference between super() and this() in java Program On other hand super keyword represents the current instance of a parent class. this keyword used to call default constructor of the same class. super keyword used to call default constructor of the parent class.
The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.
Because your method m0
in class B is private, it is not overridden by class D.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With