Skip to content
Related Articles

Related Articles

Accessing Grandparent’s member in Java using super
  • Difficulty Level : Easy
  • Last Updated : 05 Feb, 2021

Directly accessing Grandparent’s member in Java:

Predict the output of the following Java program.

Java




// 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()
    {
        // Trying to access Grandparent's Print()
        super.super.Print();
        System.out.println("Child's Print()");
    }
}
 
public class Main {
    public static void main(String[] args)
    {
        Child c = new Child();
        c.Print();
    }
}

Output:

prog.java:20: error: <identifier> expected
        super.super.Print();
              ^
prog.java:20: error: not a statement
        super.super.Print(); 

There is an error at the 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 the inheritance hierarchy. In Java, we can access grandparent’s members only through the parent class. 

For example, the following program compiles and runs fine. 



Java




// 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()

 

Why doesn’t java allow accessing grandparent’s methods? 

It violates encapsulation. You shouldn’t be able to bypass the parent class’s behavior. It makes sense to sometimes be able to bypass your own class’s behavior (particularly from within the same method) but not your parent’s. 

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 Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :