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(); } } |
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(); } } |
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.
Recommended Posts:
- Difference between super and super() in Java with Examples
- Access Super Class Methods and Instance Variables Without super Keyword in Java
- Using the super Keyword to Call a Base Class Constructor in Java
- Parent and Child classes having same data member in Java
- Super Keyword in Java
- Difference between super() and this() in java
- super and this keywords in Java
- super keyword for Method Overloading in Java
- Using underscore in Numeric Literals in Java
- Producer-Consumer solution using threads in Java
- Copying file using FileStreams in Java
- Swap two Strings without using third user defined variable in Java
- File handling in Java using FileWriter and FileReader
- Simple Calculator using TCP in Java
- Using final with Inheritance in Java
- Calling an External Program in Java using Process and Runtime
- Creating Frames using Swings in Java
- Java program to check palindrome (using library methods)
- Mutation Testing in Java (Using Jumble)
- How to rename all files of a folder using Java?

