何时防止类继承? [英] When to prevent class inheritance?

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

问题描述

我最近被告知面向对象编程的一个很好的做法你应该总是允许继承你的类。我真的不这么认为,但我没有坚定的理由。

I've been told recently a good practice in object oriented programming that you should always allow inheritance from your classes. I really don't think so, but I have no solid arguments on my mind.

真实世界阻止继承的例子


  1. No C ++ STL类(专用类模板)允许继承(具有非虚拟析构函数)。

  2. Java有 final 类修饰符,适用于许多标准组件,例如 java.lang.String

  1. No C++ STL class (specialized class template) allows inheritance (having non-virtual destructors).
  2. Java has its final class modifier that applies to many standard components, like java.lang.String.

可能的原因我认为:


  1. 安全性,因为子类可能有权访问敏感的内部。 (我不这么认为 - 他们不会访问私人会员。)

  2. 性能,因为子类可能会通过覆盖某些内容来破坏我们的高效实现成员函数。 (儿童不会覆盖非虚拟功能。)

  3. 强制执行合成而非继承。 (我完全同意。我们不应该在不需要的情况下赞成继承。)

  1. Security, since subclass might have access to sensitive internals. (I don't think so -- they won't access private members.)
  2. Performance, since a subclass could mess up our efficient implementations by overriding some of the member functions. (Children won't override non-virtual functions.)
  3. To enforce composition over inheritance. (I fully agree. We shouldn't favor inheritance when it's not needed.)

所以我的问题是:在什么情况我应该故意阻止继承吗?

推荐答案

事实上,我试图遵循的做法,以及Josh布洛赫在他的 Effective Java 一书中建议,与你被告知的完全相反:除非你考虑过继承,否则设计你的类是为了继承,并记录你的类必须如何继承,你应该总是禁用继承。

In fact, the practice that I try to follow, and that Josh Bloch recommends, in his Effective Java book, is exactly the inverse rule of the one you've been told: Unless you have thought about inheritance, designed your class to be inherited, and documented how your class must be inherited, you should always disable inheritance.

我建议你阅读有效Java的这一章(你不会后悔买它),并把它展示给那些告诉你这个规则。

I would recommend reading this chapter of Effective Java (you won't regret buying it), and showing it to the person who told you about this rule.

不允许继承的最明显的原因是不变性。不可变对象易于使用(只有一个状态),可以缓存,在许多对象之间共享,并且本质上是线程安全的。如果该类是可继承的,那么任何人都可以通过添加可变属性来扩展该类并使其可变。

The most obvious reason to disallow inheritance is immutability. An immutable object is simple to use (only one state), can be cached, shared between many objects, and is inherently thread-safe. If the class is inheritable, anyone can extend the class and make it mutable by adding mutable attributes.

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

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