kzs
kzs

Reputation: 1109

attribute having multiple types in class diagram

In UML class diagram, is it possible to represent an attribute that can have multiple types? For example, MyClass has an attribute named MyAttribute. How can I specify in class diagram that MyAttribute can assume float or string type value? An alternate option is to write MyAttribute: (https://learn.microsoft.com/en-us/visualstudio/modeling/uml-class-diagrams-guidelines?view=vs-2015), i.e. not specifying the type, but not specifying the type may create problems if people start to use their own types.

Thanks in advance.

Upvotes: 3

Views: 3017

Answers (3)

Jim L.
Jim L.

Reputation: 6529

One way to do this is to model a union of two different data types. You would define a data type that has two specializations, create a generalization set that is {complete, disjoint}, make the general data type abstract, and use the general data type as the attribute’s type.

You may have trouble convincing a code generator to map this correctly to a programming language, such as C++ or XSD, which can both represent this construct, but the UML would be perfectly clear to any reader.

Upvotes: 3

qwerty_so
qwerty_so

Reputation: 36333

When you're dealing with untyped languages (like e.g. Python), none of your attributes have a specific type. In any typed language you decide at compile time which type an attribute can take. I don't know of any language that allows a set of types to be assigned to any attribute.

Assuming you're talking about untyped languages, you would add a constraint to your generally untyped attributes telling something like { must take either type A or B }. Of course, the compiler/interpreter will not help you in checking that constraints.

Upvotes: 0

Red Beard
Red Beard

Reputation: 3506

A UML Attribut or Property can only have one type.

So if you want, for example, to allow both String and Float values you have to type your attribute with an Interface common to both of them like Object for example. But of course, it will less precise because you allow other kind of values....

Upvotes: 1

Related Questions