Effective Java 17 Design and document for inheritance or else prohibit it

Principles

  1. The class must document its self-use of overridable methods.
  2. A class may have to provide hooks into its internal workings in the form of judiciously chosen protected methods.
  3. The only way to test a class designed for inheritance is to write subclasses. You must test your class by writing subclasses before you release it.
  4. Constructors must not invoke overridable methods. This happens when there is a method which can be override by subclass calls the subclass's constructor within it. Sample violates this rule:

       

    public class Super {

    // Broken - constructor invokes an overridable method

    public Super() {

    overrideMe();

    }

    public void overrideMe() {

    }

    }

    public final class Sub extends Super {

    private final Date date; // Blank final, set by constructor

    Sub() {

    date = new Date();

    }

    // Overriding method invoked by superclass constructor

    @Override public void overrideMe() {

    // This will fail in the constructor of the Super class.

    System.out.println(date);

    }

    public static void main(String[] args) {

    Sub sub = new Sub();

    sub.overrideMe();

    }

    }

  5. The Cloneable and Serializable interfaces present special difficulties when designing for inheritance. So it's not good idea for a class designed for inheritance to implement either of these inheritance. neither clone nor readObject may invoke an overridable method, directly or indirectly. In the case of the readObject method, the overriding method will run before the subclass's state has been deserialized. In the case of the clone method, the overriding method will run before the subclass's clone method has a chance to fix the clone's state.
  6. If you decide to implement Serializable in a class designed for inheritance and the class has a readResolve or writeReplace method, you must make the readResolve or writeReplace method protected rather than private. If these methods are private, they will be silently ignored by subclasses.

   

Summary

  1. Designing a class for inheritance places substantial limitations on the class.
  2. The best solution to this problem is to prohibit subclassing in classes that are not designed and documented to be safely subclassed. Two ways to accomplish this:
    1. Declare the class final.
    2. Make all the constructors private or package-private.
  3. Separate ordinary API documentation from information of interest only to programmers implementing subclasses.

   

   

   

   

作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/haokaibo/p/design-and-document-for-inheritance-or-else-prohibit-it.html