Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor change of wording

...

Similarly, classes can rely on invariants to properly implement their public interfaces. These invariants might relate to the state of member fields or the implementation of member methods. Generally, classes can rely on encapsulation to help maintain these invariants, for example, by making member fields private. However, encapsulation can be incompatible with extensibility. For example, a class designer might want a method to be publicly accessible yet rely on the particulars of its implementation when using it in another method within the class. In this case, overriding the method in a subclass can break the internal invariants of the class.  Extensibility consequently carries with it two significant risks: a subclass can fail to satisfy the invariants promised to clients by its superclass, and it can break the internal invariants on which the superclass relies. For example, an immutable class that lacks the final qualifier can be extended by a malicious subclass that can modify the state of the supposedly immutable object. Furthermore, a malicious subclass object can impersonate the immutable object while actually remaining mutable. Such malicious subclasses can violate program invariants on which clients depend, consequently introducing security vulnerabilities. Note that the same can be said for a benign subclass that mistakenly supports mutability. These risks relate to both benign and malicious development.

To mitigate these risks, by default classes must should be declared final by default. Developers should permit extensibility only when unless there is a perceived definite need for it and must, in the class to be extensible. In that case, developers must carefully design the class with extensibility in mind. As a specific instance of this rule, classes that are designed to be treated as immutable either must be declared final or must have all of their member methods and fields declared final or private.

...