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.

Comments imported from Wordpress

bugybunny 2015-03-05 10:40:05

While you’re at it: „Kind“ should be capitalized

Peter Verhas 2015-03-05 10:43:28

Danke.

Kofa 2015-01-28 22:26:32

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/

vladmihalcea 2015-01-29 12:04:49

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".

Peter Verhas 2015-01-29 13:19:31

Thanks. Typo fixed.


Comments

Please leave your comments using Disqus, or just press one of the happy faces. If for any reason you do not want to leave a comment here, you can still create a Github ticket.