Calling grandparent methods in Java: you can not
In the article Fine points of protection I detailed how “protected” extends the “package private” access. There I wrote:
What you can do is
- Override the method in the child class or
- call the parents method using the keyword super.
And generally this is really all you can do with protected methods.
(Note that in this article I talk about methods and method calling, but the very similar statements can be said about fields, constructors.)
If you can call super.method()
to access the parent’s method()
even if the actual class has overridden it why can not you call super.super.method()
?
The absolutely correct and short answer is: because Java language does not allow you to do that. (JVM does though, but you should not.) You can not directly access grandparent methods skipping parent methods. The interesting question is: Why?
The reason lies in object orientation principles. When you extend a class you extend the defined functionality of the class.
The fact that the parent class extends another class (the grandparent class) is part of the implementation that is none of the business of any other code outside of the class. This is the basic principle of encapsulation: advertise the defined functionality of a class to the outside world but keep the implementation private. There are secrets that you keep hidden even from your son. “Nich vor dem kind.”
Generally this is the reason. If you could access the grandparent directly you would create a dependency on the implementation of the father, and this would violate encapsulation.
Reference: | Calling grandparent methods in Java: you can not from our JCG partner Peter Verhas at the Java Deep blog. |