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. “Nicht 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.
There is one exception to this: if you implement two related interfaces (say Parent and Child), both implementing the same default method (say defaultMethod()), your class must override it, too (since it’s ambiguous), but it can use the syntax Parent.super.defaultMethod() to call it.
http://www.lambdafaq.org/how-are-conflicting-method-declarations-resolved/
LikeLike
I don’t know ant German so I went on searching that German phrase, but I think it should be “Nicht vor dem kind”, instead of “Nich vor dem kind”.
LikeLike
Thanks. Typo fixed.
LikeLike
While you’re at it: „Kind“ should be capitalized
LikeLike
Danke.
LikeLike