类图 - 属性继承

发布于 2024-10-02 12:12:28 字数 81 浏览 4 评论 0 原文

我需要从一个类继承,并且只需要继承选定的属性,这可能吗?或者如果您需要所有属性,是否只能从类继承?

谢谢,

克里斯。

I need to inherit from a class and I only need to inherit selected attributes, is this possible or can you only inherit from classes if you need all of the attributes?

Thanks,

Chris.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栀子花开つ 2024-10-09 12:12:28

听起来您正在寻找实现继承而不是接口继承。请参阅此帖子了解说明,如果仍不清楚原因,请在下面注明。

鉴于您只想重用所选属性的子集,您最好使用组合而不是继承。

注意

它不能是接口继承(子类型),因为仅“继承”属性的子集,子类实例将无法替代超类实例。例如:假设子类未继承超类公开的属性A。在运行时,声明为超类类型的变量v 会绑定到子类的实例。然后表达式引用vA。完全合理的请求 - 但显然会失败。换句话说,你破坏了接口契约。谷歌“里氏替换原理”了解更多信息。

Sounds like you're looking for implementation inheritance rather than interface inheritance. See this thread for explanation, also note below if it's still not clear why.

Given that you're only looking to reuse a subset of the selected attributes you'd probably be better off using Composition instead of Inheritance.

Note

It can't be interface inheritance (subtyping) since, by only 'inheriting' a subset of attributes, a subclass instance would not be substitutable for a superclass instance. For example: assume the superclass exposed property A that the subclass didn't inherit. At run time, a variable v declared as the superclass type gets bound to an instance of the subclass. An expression then references v.A. Perfectly reasonable request - but it would obviously fail. In other words, you broke the interface contract. Google 'Liskov Substitution Principle' for more info.

冰魂雪魄 2024-10-09 12:12:28

这是可能的。当超类定义属性时,任何子类都可以重新定义该属性以具有 [0..0] 重数。因此,子类只能继承它需要的内容。 但是,正如@sfinnie提到的,这打破了里氏替换,所以你最好知道你在做什么!

我手边的 UML 2.5 规范草案说:

MultiplicityElement 可以定义其边界均为零的重数。这将允许的基数限制为 0;也就是说,它要求该元素的实例化不包含任何值。 [...]它适用于(但不限于)重新定义更通用的分类器中存在的属性。

It is possible. When a superclass defines an attribute, any subclass can redefine the attribute to have [0..0] multiplicity. Thus, the subclass can inherit only what it needs. However, as @sfinnie mentioned, this breaks Liskov Substitution, so you'd better know what you're doing!

A draft of the UML 2.5 spec I have handy says:

A MultiplicityElement can define a multiplicity both of whose bounds are zero. This restricts the allowed cardinality to be 0; that is, it requires that an instantiation of this element contain no values. [...] It applies to (but is not limited to) redefining properties existing in more general Classifiers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文