Designing classes for inheritance

2020-08-04 12:44发布

问题:

I'm reading J. Bloch's Effective Java and now I'm at the designing class for inheritance section. He described the so called self-use pattern which, as far as I got stated that we must not use overridable methods within the other overridable methods.

So my question is about how to make the client be aware about self-using. Should we mention it explicitly within Javadocs like that:

/**
* This class is self-use, thus it cannot be inherited.
*/

Or we should even refuse the temptation of the self-use.

Sample code: Should we document the class as I described above or we must avoid such self-using?

public class MyClass{

    public void overrideMe(){ 
        //something
        ovMe(); 
    }

    public void ovMe(){
         //some staff
    }
}

回答1:

As you stated, self-use is when one overridable method calls another overridable method. For example, when AbstractList.addAll calls AbstractList.add.

It's important to make sure that anyone extending the class knows this. Imagine you were writing a new list implementation based on AbstractList - you need to know whether you need to override both addAll and add, or whether you only need to override add.

Self-use is fine. What Joshua Bloch says is that if you use it, you must make sure that anyone extending the class knows about it.

There are several ways to meet this recommendation:

  • You could simply avoid self-use.
  • You could make one of the methods involved final, so it can't be overridden.
  • You could make the class final, so it can't be extended.
  • You could describe the class's self-use patterns in its Javadoc comment (meeting the requirement of letting other people know).

Also, to avoid possible confusion, note that the Java language itself does not care about self-use patterns. Nor do the compiler, the JVM, or any other piece of software. This recommendation is purely to assist programmers who might be working with your code (including you, 6 months later).



回答2:

Maybe, you can use the final for the method or the class.



回答3:

Your class should be final class.

For example you can follow up String class where you cannot override any method.



回答4:

He described so called self-use pattern which, as far as I got stated that we must not use overridable methods within the other overridable methods

/** * This class is self-use, thus it cannot be inherited. */

The only way that you can prevent programmers from not overriding an overridable (non-final) method is to mark the class as final and prevent it from getting inherited.

public final class MyClass{

    public void overrideMe(){ 
        //something
        ovMe(); 
    }

    public void ovMe(){
         //some staff
    }
}

If you mark a method as final, it is no longer overridable so it does not fit the description you have provided in your quesiton.