Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the key word super 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 am not getting how the super keyword plays the role of calling the methods of the child class instead of the parent class.

like image 988
Kumar Abhishek Avatar asked Aug 14 '15 07:08

Kumar Abhishek


People also ask

How does Super keyword work in Java?

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.

How are this () and super () used with constructors?

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.

Do you know rule for writing super () this () in a program?

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.

Can we use super super in Java?

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.


1 Answers

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

like image 127
Dakshinamurthy Karra Avatar answered Sep 21 '22 15:09

Dakshinamurthy Karra