在 Java 中禁止继承的充分理由? [英] Good reasons to prohibit inheritance in Java?

查看:30
本文介绍了在 Java 中禁止继承的充分理由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中禁止继承的充分理由是什么,例如使用 final 类或使用单个私有无参数构造函数的类?使方法最终化的充分理由是什么?

What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?

推荐答案

这里最好的参考是 Joshua Bloch 的优秀著作《Effective Java》的第 19 条,名为继承的设计和文档,否则禁止它".(这是第二版的第 17 项和第一版的第 15 项.)你真的应该读一读,但我会总结一下.

Your best reference here is Item 19 of Joshua Bloch's excellent book "Effective Java", called "Design and document for inheritance or else prohibit it". (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize.

如果祖先不是为了继承而设计的,继承的类与其父类的交互可能会令人惊讶和不可预测.

The interaction of inherited classes with their parents can be surprising and unpredicatable if the ancestor wasn't designed to be inherited from.

因此类应该有两种:

  1. 被设计为扩展,并有足够的文档来描述应该如何完成

  1. Classes designed to be extended, and with enough documentation to describe how it should be done

课程标记为期末

Classes marked final

如果您正在编写纯粹的内部代码,这可能有点矫枉过正.然而,将五个字符添加到类文件所涉及的额外工作非常小.如果您只是为内部消费而编写,那么未来的编码人员总是可以删除final"——您可以将其视为警告,说这个类的设计没有考虑到继承".

If you are writing purely internal code this may be a bit of overkill. However the extra effort involved in adding five characters to a class file is very small. If you are writing only for internal comsumption then a future coder can always remove the 'final' - you can think of it as a warning saying "this class was not designed with inheritance in mind".

这篇关于在 Java 中禁止继承的充分理由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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