Over a million developers have joined DZone.

Calling Grandparent Methods in Java: You Can Not

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.


Published at DZone with permission of Peter Verhas, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}