Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaAccessing Grandparent’s member in Java using super

Accessing Grandparent’s member in Java using super

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.
 

RELATED ARTICLES

Most Popular

Recent Comments