Accessing Grandparent’s member in Java using super
Directly accessing Grandparent’s member in Java:
Predict the output of following Java program.
// 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
filter_none
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.
// 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
filter_none
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.
Recommended Posts:
- Difference between super() and this() in java
- Super Keyword in Java
- super and this keywords in Java
- Parent and Child classes having same data member in Java
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java lang.Long.highestOneBit() method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java.util.concurrent.RecursiveAction class in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java.lang.Short toString() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java.util.concurrent.RecursiveTask class in Java with Examples



