DEV Community

Inanc Cakil
Inanc Cakil

Posted on

Is super.super.method() allowed in Java?

I encountered this question through an interview process. I thought to myself that I haven’t seen this usage and wondered what might be the reason for it to be not allowed. I didn’t know the answer. After the interview, I looked for it and found that it is, indeed not allowed in java, but why?

In C++, we can use the scope resolution operator (::) to access any ancestor’s member in the inheritance hierarchy but in Java, we can access grandparent’s members only through the parent class.

So the question is “Why is super.super.method() not allowed in Java?”

Because it violates encapsulation. Encapsulation is a principle of wrapping code and data(variables) together into a single unit. It’s one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation is often used to implement a data-hiding mechanism. This mechanism reduces the accessibility of attributes to the current class and uses public getter-setter methods to control and restrict external access to these attributes. These methods not only allow you to define which attributes can be read or updated, but it also enables you to validate the new value before changing the attribute.

With Encapsulation, the fields of a class can be made read-only or write-only and a class can have full control over what is stored in its fields.

Therefore, we shouldn’t be able to bypass the parent class’s behaviour. It makes sense to sometimes be able to bypass your own class’s behaviour (particularly from within the same method) but not your parent’s!

For example, we have a base “collection of items”, a subclass representing “a collection of red items” and a subclass of that representing “a collection of big red items”.

With super.super.add(item) we could add anything and the invariant in RedItems is broken.

Okay, but why does C++ allow this?

When I searched for this question, I found this answer:
Because c++ doesn’t care if you shoot yourself in the foot :)
I think the main reasons are the flexibility and the fact that C++ assumes we understand how to programs to the edge of bytes and RAM while Java assumes we don’t know how to program and Java doesn’t allow us to design software poorly.

This article was originally published on medium:

Top comments (0)