Java Deep

Pure Java, what else

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

5 responses to “Calling grandparent methods in Java: you can not

  1. Kofa January 28, 2015 at 10:26 pm

    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/

    Like

  2. vladmihalcea January 29, 2015 at 12:04 pm

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

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: