Accessing Grandparent’s member in Java using super
Directly accessing Grandparent’s member in Java:
Predict the output of the following Java program.
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.
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.
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.