UML Can an interface be part of an aggregation relationship? - uml

I have a top class, lets call it Car. I have an interface, lets call it ITyre and then I have two classes which implement ITyre. Lets call them Goodyear and Bridgestone.
Am I allowed to have a composition association between the interface ITyre and Car (from UML perspective, not a particular language)?

If you meant,
public class Car
{
ITyre something;
}
Yes, you can. In fact it will be good if you do it this way. So that your Car is not depending on any one particular concrete implementation. Your implementation here will give you flexibility to swap out tyres (DI or factory) irrespective of who built them.

Related

How to Show Reference type and Object type separately for same object in UML object and sequence diagram

The diagram shows sample Class diagram and usage of objects of those classes in Sequence diagram.
In the above diagram instance myCar can be referred either by reference of ShowroomItem or reference of interface Vehicle. Accordingly the clients Driver/ SalesEngineer will get functionality access.
I agree that in implementation stage (e.g. Java), type identification is not required here and we will treat myCar as instance of base type (either interface) used itself.
But in sequence diagram, (for clarity) I am unable to indicate that the reference for myCar for Driver should be of Vehicle and for SalesEngineer should be of ShowroomItem.
I searched in UML 2.0 books, I did not get suitable notation. As per current understanding, I can show it either as "myCar : Vehicle" or "myCar : ShowroomItem", but that does not indicate that its Object of Car referred as Interface. This shortcomming does not enforce that playMusic can not work when referred as Vehcile.
Is there any notation to show this kind of detail?
As I am not satisfied with any answer provided, I am trying to add following to make question more clear, address some objections raised in the answers and proposing kind of solution for experts to review.
Looking at the comments, I feel either people did not get the core question, or I failed to highlight the core issue. First let me demonstrate code does not break. following code allows SalesEngineer to access Abstraction with sell() and buy() functionality and Driver to access Abstraction with only start() and stop() functionality [designed that way]. This is a strongest feature of interfaces to publish different abstractions to different clients. Java Collections use same multiple base types namely Object and Comparable in TreeSet, one for equals() and another for compare() on entities.
package com.se.stackoverflow;
interface Vehicle {
abstract void start();
abstract void stop();
}
interface ShowroomItem {
abstract void buy();
abstract void sell();
}
class Car implements ShowroomItem, Vehicle {
// **Car IS-A Vehicle and ShowroomItem BY-DEFINITION**
// **and as per SOLID principle interface segregation**
public void start() { System.out.println("Started");}
public void stop() { System.out.println("Stopped");}
public void sell() { System.out.println("Sold");}
public void buy() { System.out.println("Baught");}
}
class SalesEngineer {
private ShowroomItem item = null;
public SalesEngineer(ShowroomItem item) { this.item = item;}
public void doTransaction() {item.buy(); item.sell();}
}
class Driver {
private Vehicle veh = null;
public Driver(Vehicle veh) {this.veh = veh;}
public boolean testDrive() {veh.start(); veh.stop(); return true;}
}
public class ShowroomOwner {
public void makeDeal(Car carForDeal) {
Driver driver = new Driver(carForDeal);
SalesEngineer engineer = new SalesEngineer(carForDeal);
if (driver.testDrive()) {
engineer.doTransaction();
}
}
public static void main(String[] args) {
// simulates client as ShowroomOwner to save space
new ShowroomOwner().makeDeal(new Car());
}
}
After referring "UML 2 and Unified Process" by Jim Arlow, I found we can show changing states over life line in sequence diagrams. I feel similar notation we can use to show changing types object [i havnt seen this documented in UML anywhere but its my suggestion to UML group].
e.g. here myCar is Object of its class Car (class of object can never be changed) but its reference type varies as per the left side like ShowroomItem or Vehicle.
May be following sequence diagram can show it. [Example classes are just indicative to highlight auto type casting effects]
UML notation issue
You need to make choices about the type you want to show for each lifeline of a sequence diagram, because UML only allows a single one. Since myCar is a Car which implements Vehicle and ShowroomItem you may chose any of the 3 types.
Once the type chosen, UML has no way to provide an alternate view on the type in the same diagram. You can show the scenario with myCar being a Car. But the other lifelines must comply with the interface they know (provided no other usage dependency give them access to the full Car) and it's up to you to ensure consistency. This may be error prone, as you have demonstrated with playMusic().
You way address your concern with one or several notes in the diagram to remind the readers in plain text of the interface-related constraints. But a far better approach would be to keep it simple and show the interaction between SalesEngineer and Car and between Driver and Car in two separate diagrams. This is closer to the reality of your design, and promotes sound separation of concerns.
OOP Design issue
Qwerty_so and Bruno have already pointed to the weaknesses in your design. I fully agree with them. Indeed, a Car is a Vehicle. But a Car is not a ShowroomItem: a Car can temporarily have the role of a showroom item. Or converesely, a showroom item may correspond at a given time to a specific car.
If a car is not a showroom item it should neither inherit from such a class nor implement such an interface. Hence, prefer composition over inheritance, for example:
SalesEngineer trades in ShowroomItem
CarForSale implements ShowroomItem
CarForSale is associated to one Car
Driver drives a Vehicle (caution: bias towards rolling vehicles, because there's no driver on a plane ;-) )
Car implements Vehicle
Car can be associated to a CarForSale (but only if it is for sale by a SalesEngineer)
This design ensures better separation of concerns. For example, you can sell() or buy() only cars that are really for sale and not any car. Only cars for sale will have a price.
The other advantage is that you can show this full picture in a more robust way in a single sequence diagram since the different responsibilities are implemented by different objects.
First your class diagram is wrong, a car is not a ShowRoomItem, a car is the same before and after it is sail/buy, in your case the car will have to stop (may temporary) to be a ShowRoomItem since it is sail/buy. The fact it is a show room item is not a type but in the best case a state, but for me to have that state as an attribute of the car is a wrong choice too.
Second the actual instance the driver or sales engineer accesses is a car, and the car does not care who uses it, the radio does not disappear when the person is a sales engineer, so the car always accept to play radio if enough pre conditions are on (battery have power, may be key turn on etc)
The fact there are restrictions depending on who is the person must not be done at the level of the car, else this is out of the reality and fully artificial, but at the level of the person/role.
In UML for that kind of restrictions you can use constraints.
Since Car inherits (per your UML) from ShowRoomItem it will also have the sell() operation and the SalesEngineer can use it.
I think your model is just strange. A car which has a sell() operation is definitely one I would not buy. In other words: your class model is broken.

What is appropriate UML class relationship?

In my case, what is appropriate relationship between CarBuilder and SuperCar (SportCar as well)?
Explanation: CarBuilder holds an array of Car class's instance but it doesn't construct any instance of Car class. Instead, it constructs SportCar, and SuperCar classes' instances by directly call CreateInstance() method of these two classes.
Class Diagram:CarBuilder
In your question you are describing three different relationships -- a compositional one (that you already have), and then two others to the constructors of SuperCar and SportCar. So I'd just add an association to SuperCar and SportCar from CarBuilder.
Incidentally, it seems unlikely that you'd only ever have a car composed within CarBuilder -- maybe you mean a (weak) aggregate rather than a composition? Surely a car can exist outside CarBuilder? Also, this looks like a partial implementation of the strategy pattern, might be worth looking whether that's relevant.

Is calling a method considered a relationship on a class diagram?

I'd like to know if calling a method from a different class is considered a relationship on a class diagram.
Regards.
Not always. Some types of relationships (e.g. a uses b, a notifies b, etc) can be implemented or supported by calling of an object's method thoough.
It depends on how closely the class diagram represents relationships. That is a design choice.

UML definition - Generalization, aggregation and abstract classes

I'm a bit confused regarding Generalization, Aggregation and abstract classes in UML.
By Generalization, I can understand that it's a "is a"-relationship. A student is a Person - and a teacher is a Person. So Person would be the superclass, whereas student and teacher are both subclasses.
By Aggregation, this is what I understand: It's a "softer" relation compared to composition. An example could be: You can have a hand with no fingers (aggregation) but you can't have fingers without a hand (composition).
And then I am completely lost on abstract classes. What are the characteristics of abstract classes? I'd like an example on this if possible.
But am I on the right track here? This is how I understand these terms.
You understand Generalization.
Associations may be Aggregations or Compositions (or neither). This is a good example that Tom Pender used to use. Suppose you have a Car class. That Car class "has" a steering wheel, seats, two axles, four wheels, and so on. If you're creating that Car in a manufacturer context, the relationship between all of those would be Composition: the lifetime of all the car's parts (at your manufacturer) is tied to the lifetime of the car. From the standpoint of the manufacturer, the lifetime of the car and all its parts ends when you deliver it to a dealer.
Now, let's suppose you're the owner of a junkyard. In this case, a car still "has" all those parts, but they have a lifetime of their own: you can sell parts off of the car, and even make them part of some other car if you need to. The relationship between the car and those parts is Aggregation, because the lifetime of the parts isn't tied to the lifetime of the car itself.
So, you can see that the same car could actually be modeled in two different ways depending on context.
As for abstract classes: an abstract class is simply a class that defines methods and/or properties while requiring that they can only be implemented in subclasses. It's easiest to explain why with interfaces. Interfaces are abstract classes, with the added proviso that NONE of the methods or properties can be implemented directly in the class (you might say it's a definition of how to define a subclass). Here's where they come in useful.
Suppose I want to define an Animal class. What do animals do? Well, they move. They bite. (They do other things too, of course, but let's stick to Move and Bite.) If I create an Animal interface, I'm saying "here's what an animal does. If you want to be an animal, you have to also do these things. However, I'm not going to tell you how to do them." So, I create an iAnimal interface, with two methods, Move and Bite. As an interface, I don't provide any sort of implementation, just empty procedures.
Now, suppose I have two animals, a Flea and a TRex. Clearly, Fleas and TRexes don't have anything in common in the way that they move or the way that they bite, but they both do both. I'll have Flea and TRex inherit or "implement" the interface, providing implementations of Move and Bite appropriate for the type of animal.
The advantage of this is that clients of my flea and trex don't have to know which one they are dealing with. They can create an iAnimal, inject an instance of Flea or TRex as appropriate, and safely call iAnimal's Move and/or Bite methods without having to worry about whether they're supported or not. (This is what we mean by "polymorphism").
So, interface implementation is a form of Generalization (more correctly Specialization, going the other way), as you have probably already surmised.
From here, an "abstract class" is simply any class with any method or attribute defined that has to be inherited to be implemented. Therefore, as I have said, interfaces are abstract classes. However, in general usage, an abstract class is taken to mean one that is not also an interface, i. e. one that has some concrete methods or attributes. Most programming languages adhere to this definition.

How to define this class relationship

This my UML class diagram (URL)
In above diagram, ChildParent (or Child1, Child2, and Child3) can only be initialized in MainObject->create_new_object() and store it in class Library through ObjectData->lib->add_object(key, newObject).
So, how to define UML class relationship between ChildParent, Library, and MainObject?
Thank you
Relationships between classes are structural, not behavioral. The MainObject is creating it, but it is not controlling its lifespan nor does it own it in any way. After creating is it handed over to the ObjectData, transported to the Library and stored there. There is a behavioral relationship between the MainObject and the ChildParent object, but there is not a structural relationship between the two of them. I should not depict any relationship between them.
The Library is storing it. This is a typical whole part relationship and structural. What is a library without books? Therefor would I make use of the aggregation type of relation. It is not the composition, because the Library does not control the lifespan of any ChildParent or Child object nor does it imply that the ChildObject will be destroyed when the Library object is destroyed. That might happen, but given the presented data is that not clear to me.
EDIT as a reply to a comment:
Class diagrams show the structural relationships between classes, not their usage. When a class implements an interface, then will you see that relationship in the diagram. In the code (the behaviour) might you not see this relationship, because the implementation is hidden in a factory method or provided by a IoC container or it might even be a relationship that is never used.
What is the relationship between a class (the caller) that is picking a class (the callee) from a library and between the caller and the library?
It is obvious that the caller and the library have a behavioral relationship. If the module changes, can the caller get his callee from some other class. Therefor will the library and the caller have no relationship in the class diagram.
There is a structural relationship between the caller and the callee. The caller needs the callee. Your comment does not specify the exact relationship between them, but there is a relationship. The weakest form is the dependency relationship. An example in connection with a library is that a person is lending a book from a library. When he starts to read the book, is the callee used. It does not belong intrinsically to the person as a whole, but it does belong to a certain method of the person class.
There are a lot of ways to implement a library. It can be for instance a wardrobe. What is the relationship between a person in the military and his uniforms? He needs to wear some uniforms in certain situations, yet in other situations are those uniforms forbidden to wear. Wearing an uniform is a part of the class military. You can not be in the military without wearing an uniform in the time of duty. The moment you are out of the military are you not allowed to wear the uniform anymore. Hence has a military a compositional relationship with that uniform from his wardrobe.
There are more types of relationships possible between the caller and the callee. You can not say it at forehand. You must answer it the same way as any other relationship. The first question is very clear: is this a structural relationship or not? Keywords like 'is a' and 'has a' depict a structural relationship. Keywords like 'uses', 'asks', 'picks from' show a behavioral relationship. Have you concluded that it is a structural relationship, then should you find out what the dependency between the two classes is.

Resources