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