设计继承类 [英] Designing classes for inheritance

查看:137
本文介绍了设计继承类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读J. Bloch的Effective Java,现在我正处于继承部分的设计课程中。他描述了所谓的自用模式,据我所知,我们不能在其他可覆盖的方法中使用可覆盖的方法。

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.

所以我的问题是关于如何让客户了解自我使用。我们应该在 Javadocs 中明确提到它:

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
    }
}


推荐答案

如上所述,自我使用是指一个可覆盖的方法调用另一个可覆盖的方法。例如,当 AbstractList.addAll 调用 AbstractList.add

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

确保任何扩展课程的人都知道这一点很重要。想象一下,你正在编写一个基于 AbstractList 的新列表实现 - 你需要知道是否需要覆盖 addAll 添加,或者您是否只需要覆盖添加

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.

自用就好了。 Joshua Bloch所说的是如果你使用它,你必须确保任何扩展课程的人知道它

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:


  • 你可以简单地避免自用。

  • 你可以制作一个所涉及的方法 final ,因此无法覆盖。

  • 你可以让班级最终,因此无法扩展。

  • 您可以在其Javadoc评论中描述该类的自用模式(满足让其他人知道的要求) 。

  • 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).

另外,为避免混淆,请注意 Java语言本身并不关心自我使用模式。编译器,JVM或任何其他软件也不是。此建议纯粹是为了帮助可能正在使用您的代码的程序员(包括您,6个月后)。

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).

这篇关于设计继承类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆