Home > Java > javaTutorial > Why is `super.super.method();` Not Allowed in Java?

Why is `super.super.method();` Not Allowed in Java?

DDD
Release: 2024-12-23 11:13:09
Original
999 people have browsed it

Why is `super.super.method();` Not Allowed in Java?

Why is super.super.method(); Prohibited in Java?

The use of super.super.method(); in Java is forbidden due to encapsulation concerns. Encapsulation aims to prevent circumventing the parent class's behavior.

While it's sometimes reasonable to bypass one's own class's behavior (within the same method), it's crucial not to bypass the parent's behavior. Consider the following class hierarchy:

  • Collection: Base class for any item collection
  • RedCollection: Subclass representing a collection of red items
  • BigRedCollection: Subclass of RedCollection representing a collection of big red items

It's logical to define the following methods:

  • Collection#add(Item): Adds an item to the collection.
  • RedCollection#add(Item): Overridden method that ensures added items are red.
  • BigRedCollection#add(Item): Overridden method that ensures added items are big and red.

This ensures that the subclasses adhere to the constraints imposed by their parent classes.

However, if super.super.add() were allowed, a malicious NaughtyCollection subclass could bypass the RedCollection's red item requirement:

  • NaughtyCollection#add(Item): Disregards the red item requirement, adding any item.

This would break the invariant established by RedCollection, creating a collection of items that might not be red.

Therefore, super.super.method() calls are prohibited in Java to maintain encapsulation and enforce class behaviors.

The above is the detailed content of Why is `super.super.method();` Not Allowed in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template