UML Design class diagram: Class with another class as attribute

class-diagramoopuml

I'm having a pretty hard time trying to figure out how to model a certain scenario as a UML design class diagram.

Suppose I have the following situation:

I have a class named CPoint that has two attributes: x and y (coordinates in a R2 plane). Additionally, I have a class named CLine that should have two CPoint as attributes.

This is pretty straight forward to code (I'll use C++ in my example):

class CPoint{
    float x;
    float y;
    //Constructor, gets and sets here
}

And for CLine:

class CLine{
    CPoint p1;
    CPoint p2;
    //Constructor, gets and sets here
}

Now my question is: How do I model such a thing in UML?

I thought of something similar to this:

Attempt 1

But then I was told that this is violating the principles of object oriented modeling, so then I did this:

Attempt 2

But it does not convince me at all. Additionally, I was reading about design patterns and came to this UML design while reading about singletons:

Singleton design pattern

Which makes me think my initial approach was just right. Additionally, I'm able to see that my first approach is just alright if I think about it as a C++ program. In Java, however, I'd still have to create the object by doing new CPoint(0, 0) in the CLine's constructor. I'm really confused about this.

So, how do I model this situation? Am I perhaps being too concrete when I attempt to model the situation?

Thanks in advance! This isn't letting me sleep at night

Best Answer

In UML an association or an attribute (property) are more or less the same thing, so they are both correct.

In most UML tools however they are different things.

There is not really a rule here, but there are best practices. My UML Best Practice: Attribute or Association says:

Use Associations for Classes and Attributes for DataTypes

Related Topic