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:
It's logical to define the following methods:
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:
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!