2
votes

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://docs.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.

3
How would you do it in (OO) code? Answering that question often helps when looking for a way to model it in UML.Geert Bellekens
I thought during the instantiation of the object, the entity instantiating it will have the independence to either use a float or string for MyAttribute.kzs
I don't understand what you mean by that, sorry.Geert Bellekens
MyObject:MyClass that will be instantiated will have an attribute MyAttribute for which either float or string value is allowed.kzs
You can't do it in Python either. The attributes in an untyped language have no type al all. That is different from either string or float.Geert Bellekens

3 Answers

2
votes

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.

1
votes

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

1
votes

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.