从具体类继承的好例子? [英] Any good examples of inheriting from a concrete class?

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

问题描述

背景:

作为Java程序员,我从接口广泛继承(而不是实现),有时我设计抽象基类。然而,我从来没有真正感觉到需要对一个具体的(非抽象的)类进行子类化(在这样的情况下,它再次证明了另一个解决方案,比如将会更好)。

As a Java programmer, I extensively inherit (rather: implement) from interfaces, and sometimes I design abstract base classes. However, I have never really felt the need to subclass a concrete (non-abstract) class (in the cases where I did it, it later turned out that another solution, such as delegation would have been better).

所以现在我开始觉得几乎没有任何继承的情况从一个具体的班级是适当的。一方面, Liskov替代原则(LSP)似乎几乎不可能满足非平凡类;另外许多其他

So now I'm beginning to feel that there is almost no situation where inheriting from a concrete class is appropriate. For one thing, the Liskov substitution principle (LSP) seems almost impossible to satisfy for non-trivial classes; also many other questions here seem to echo a similar opinion.

所以我的问题:

在哪种情况下(如果有的话)从具体类继承是否有意义?
你能给出一个继承自另外一个具体类的具体的现实世界的例子,你觉得这是一个给定约束的最好的设计?我特别感兴趣的是满足LSP的例子(或者满足LSP似乎不重要的例子)。

In which situation (if any) does it actually make sense to inherit from a concrete class? Can you give a concrete, real-world example of a class that inherits from another concrete class, where you feel this is the best design given the constraints? I'b be particularly interested in examples that satisfy the LSP (or examples where satisfying LSP seems unimportant).

我主要有一个Java背景,但我有兴趣

I mainly have a Java background, but I'm interested in examples from any language.

推荐答案

您通常有一个骨骼实现用于界面。如果您可以在没有抽象方法(例如通过钩子)的情况下提供可扩展性,则最好使用非抽象骨架类,因为您可以实例化。

You often have a skeletal implementations for an interface I. If you can offer extensibility without abstract methods (e.g. via hooks), it is preferable to have a non-abstract skeletal class because you can instantiate it.

一个例子是一个转发包装类,可以转发到具体类的另一个对象 C 实现 I ,例如使装饰或简单的代码重用 C 而不必继承 C 。您可以在有效Java 项目16中找到这样的示例,有利于构建继承。 (我不想在这里发布版权,但它真的只是转发所有方法调用到包装的实现)。

An example would be a forwarding wrapper classes, to be able to forward to another object of a concrete class C implementing I, e.g. enabling decoration or simple code-reuse of C without having to inherit from C. You can find such an example in Effective Java item 16, favor composition over inheritance. (I do not want to post it here because of copyrights, but it is really simply forwarding all method calls of I to the wrapped implementation).

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

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