Accessing Grandparent’s member in Java using super

Directly accessing Grandparent’s member in Java:

Predict the output of following Java program.

filter_none

edit
close

play_arrow

link
brightness_4
code

// filename Main.java
class Grandparent {
    public void Print() {
        System.out.println("Grandparent's Print()");
    }
}
   
class Parent extends Grandparent {
    public void Print() {       
        System.out.println("Parent's Print()");
    }
}
   
class Child extends Parent {
    public void Print() {
        super.super.Print();  // Trying to access Grandparent's Print()
        System.out.println("Child's Print()");
    }
}
   
public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.Print();
    }
}

chevron_right


Output: Compiler Error
There is error in line “super.super.print();”. In Java, a class cannot directly access the grandparent’s members. It is allowed in C++ though. In C++, we can use scope resolution operator (::) to access any ancestor’s member in inheritance hierarchy. In Java, we can access grandparent’s members only through the parent class. For example, the following program compiles and runs fine.

filter_none

edit
close

play_arrow

link
brightness_4
code

// filename Main.java
class Grandparent {
    public void Print() {
        System.out.println("Grandparent's Print()");
    }
}
   
class Parent extends Grandparent {
    public void Print() {
        super.Print();
        System.out.println("Parent's Print()");
    }
}
   
class Child extends Parent {
    public void Print() {
        super.Print();
        System.out.println("Child's Print()");
    }
}
   
public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.Print();
    }
}

chevron_right


Output:

Grandparent's Print()
Parent's Print()
Child's Print()

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


26


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.