UML2 Class Diagram in Java

In the modelling world Class diagram forms the major chunk of the Unified Modelling Language (UML) architecture diagram. In this article we are planning to show some of the key usage of the class diagram and how they can be represented in Java. This article can be used as a reference for your modelling.
UML was developed by Grady Booch, Ivar Jacobson, Jim Rumbaugh at Rational Software in 1990. To get more details on the UML development, it’s progress and story of standardisation by OMG (please don’t confuse this with the current SMS language of ‘Oh My God’, it is Object Management Group (OMG)) you can refer to Martin Fowler’s UML Distilled book . He has explained very clearly about the practical use of the various UML diagrams in modelling.
In this article we will go straight to the point making it a crisp reference document.

Class Diagram Example:

Class Diagram

Class Diagram Example

 Car.java

public class Car {
	private String carColor;
	private double carPrice = 0.0;
	public String getCarColor(String model) {
		return carColor;
	}

	public double getCarPrice(String model) {
		return carPrice;
	}
}

The above example of Car class is self explanatory. The Car class has private instance variables carColor, carPrice denoted by (-) in the UML Class diagram. Similarly if this was public then it would have been represented as (+), if was protected then it is denoted by (#). The package visibility is defined by (~).

Java visibilityUML Notation
public+
private-
Protected#
package~

The return type of the instance variables or the methods are represented next to the colon (:) sign.
Structure:
[visibility] [attribute name] [multiplicity] [:type [=default value]] {property string}
Example: carPrice : double = 0.0

Representing Static variable or static operation:
The static data is represented with an underline. Let’s take the below example.

Class diagram

Class diagram

public class Employee {
	private static String department = "R&D";
	private int empId;
	private Employee(int employeeId) {
		this.empId = employeeId;
	}
	public static String getEmployee(int emplId) {
		if (emplId == 1) {
			return "idiotechie";
		} else {
			return "Employee not found";
		}
	}
	public static String getDepartment() {
		return department;
	}
}

Association:
The association represents the static relationship between two classes along with the multiplicity. E.g. an employee can have one primary address associated with it but can have multiple mobile numbers.
Association are represented as thin line connecting two classes. Association can be unidirectional (shown by arrow at one end) or bidirectional (shown by arrow at both end).
Multiplicity defines how many instances can be associated at any given moment.

0..1No instances or one instanceA flight seat can have no or one passenger only
1Exactly one instanceAn order can have only one customer
0..* or *Zero or more instancesA class can have zero or more students.
1..*One or more instances (at least one)A flight can have one or more passenger

The unidirectional relationship shows that the source object can invoke methods of the destination class. In Java a possible example can be the instance variable of source class referencing the destination class.

Association Example

Association Example

 

public class Customer {
private String name;
private String address;
private String contactNumber;
}

public class Car {
	private String modelNumber;
	private Customer owner;
}

Let’s look at an example of bidirectional association:

Bidirectional association

Bidirectional association

public class Customer {
private String name;
private String address;
private String contactNumber;
private Car car;
}

public class Car {
	private String modelNumber;
	private Customer owner;
}

In the bidirectional association each of the class in this relationship refers to each other by calling each others method. In the above Java example it is depicted as instance variable of Car class in called inside the Customer class and vice versa.
In the above example the car and owner refers to the roles and is depicted by the name of instance variable in the code.
Multiplicity:
Assume a scenario where a customer has multiple cars. How do we represent this situation in Java and UML?

Multiplicity in association

Multiplicity in association

The above diagram explains a unidirectional association with a one to may relationship. Both use of ArrayList and Array is for illustration purposes only.

Car.java

public class Car {
	private String brand;

	public Car(String brands){
		this.brand = brands;
	}
	public Car() {
	}
	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

}

Customer.java

public class Customer {
	private Car[] vehicles;
	ArrayList<Car> carList = new ArrayList<Car>();
	public Customer(){
		vehicles = new Car[2];
		vehicles[0] = new Car("Audi");
		vehicles[1] = new Car("Mercedes");

		carList.add(new Car("BMW"));
		carList.add(new Car("Chevy"));
	}
}

Generalization
This property represents the inheritance feature of the object oriented concept. In Java this can relate to the “extends” keyword. The inheritance should ideally follow the Liskov Substitution Principle i.e. the subtype should be able to substitute for its supertype. It helps to make the code implicitly follow the Open Close Principle i.e. Open for extension but closed for modification.

Generalization

Generalization

 

public class Car {
	private String model;
	public void printPrice() {
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
}

public class hatchback extends Car {
	private String model;
	public void printPrice() {
		System.out.println("Hatchback Price");
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
}

Realization:

This is related to the relationship between the class and the interface. The realization is equivalent to the “implements” keyword in Java.

Realization in Java

Realization in Java

Realization can also be represented as :

Realization - alternative

Realization – alternative

This is very straight forward implementation so hopefully there will ne no code provided. Unlike Generalization in this case the arrow is dashed.
Dependency
Dependency is a relationship that shows that a class is dependent on another class for its existence or implementation. Dependency relationship is shown as a dotted line with an arrow from source class to the dependent class.
In Java we can consider the dependency relationship if the source class has a reference to the dependent class directly or source class has methods through which the dependent objects are passed as a parameter or refers to the static operation’s of the dependent class or source class has a local variable referring to the dependent class etc.

 

Dependency

Dependency

The above diagram satisfies dependency relationship as the source class Order passes the PaymentSystem reference through the processPayment().

public class PaymentSystem {

}

public class Order {
public void processPayment(PaymentSystem ps){

 }
}

Aggregation:
This shows “has a” relationship. It is a form of association relationship. This relationship highlights that a whole is made of its parts. So if a whole is destroyed the part still remains.
In UML this is represented through a hollow diamond with the diamond symbol pointing towards the whole.
In case of Java the aggregation follows the same structure as association. It is represented through the instance variables of a class.

Aggregation

Aggregation

public class Student {

}

public class School {
	private Student student;
}

In this case a student is a part of the School. However during design it is preferred to use association instead of aggregation as it is not a recommended option.

Composition:
This is again a whole or part relationship where if the whole is destroyed then the part cannot exist independently. Another important point about Composition is that the part at any point in time can have only one owner. E.g. A person can be an employee of one company at any point in time due to contractual obligations. That person cannot hold dual work authorisation. If the Company goes bankrupt the employee of this company does not exist and will be fired.
The composition is represented as a filled diamond with data flowing in single direction from the whole to the part.
The composition in Java is represented in the same form as aggregation with help of instance variables.

Composition

Composition

public class Employee {

}

public class Company {
	private Employee[] employee;
}
Question: Can a singleton class be represented as Aggregation?
Answer: No. The aggregation does not support cyclic relationship. However in case of Singleton it requires a cyclic relationship with itself.

This article can be used as a reference article while coding from design in Java. Hope our readers will find this article useful.

13 Responses to “UML2 Class Diagram in Java”

  1. Mario Guerrero

    Dec 30. 2012

    Very good and cler.

    Thanks.

    Reply to this comment
  2. george

    Jan 07. 2013

    Nice post, easy to dive into the main concepts. If class diagrams are just a subset of UML, they are commonly used to design/describe most of our domain models (i.e the handled data), even if the whole system (processes, use cases…) is not modeled. That’s why it’s pretty cool to learn class modeling from the developer’s point of view: with a basic implementation in Java.

    For those who want to create an UML class diagram online and to get the corresponding Java code, I recently discovered genmymodel (http://www.genmymodel.com). It’s in beta but already allows to make a class diagram/model (not only a drawing), and to generate code from it. It makes sense for further reading.

    George

    Reply to this comment
    • Mainak

      Jan 09. 2013

      Hello George,

      I explored the genmymodel.com website and I must say this is a very nice initiative. Good luck.

      Reply to this comment
  3. Joseph

    Mar 21. 2013

    Hey, It is very nice to learn UML diagrams with Java examples.
    Aggregation and Composition can you give much clear example…?

    Reply to this comment
  4. Ganesh

    Apr 17. 2013

    Very nice exploration and very very use for Us. thanks

    Reply to this comment
  5. mallikarjun

    May 17. 2013

    Hi..
    Nice Post all…Thanks for u r service….This kind of explanation is usefull for both learners and experienced persons also…
    Why don’t u provide explanation on other design patterns all structural and behavioural and j2ee design patterns this is will be really help full..

    Reply to this comment
    • IdioTechie

      May 18. 2013

      Thanks Mallikarjun for your interest. I will be writing on few other design patterns shortly. Keep watching this space.

      Reply to this comment
  6. Maher

    Jul 13. 2013

    Thanks Idio Techie very usefull explanation , i have some other cases i don’t know how te depict them in an class diagram, if you can help me :

    1) A class that extends from an imported class , below is an exemple code :

    package Mypackage;

    import javolution.xml.XMLBinding;

    public class SctpXMLBinding extends XMLBinding {

    }

    2) How to represent two classes that have association relation and dependency relation at the same time

    exemple code

    public class A { }

    public final Class B {

    private A That_class;

    protected B ( A That_class ) {
    this.That_class = That_class ;
    }

    }

    3) How to represent a class that has an association with an imported class :

    import javolution.text.TextBuilder;

    public my_class {

    private final TextBuilder persistFile = TextBuilder.newInstance();

    public my_class() { }

    }

    Thanks in advance
    Regards

    Reply to this comment
    • IdioTechie

      Jul 15. 2013

      Hello Maher.
      Thanks for visiting our website. Please find below the answers to your above query:
      1) This is a straight forward Generalization. Even if the class is imported you are using extend keyword to inherit from XMLBinding.
      2) In this case the association gets more priority over dependency. Dependency is more generic and association is more specific and stronger type relationship. So you will need to use association diagram here.
      3) This is again an association relationship. You can refer this to my example of Car which is associated to the Customer through owner. Similarly my_class is associated to the TextBuilder class through persistFile.
      Hope this helps.

      Please keep visiting this space for more article and don’t forget to subscribe to our newsletter.
      Thanks

      Reply to this comment
  7. Sushant

    Sep 03. 2013

    Good article,concepts are very nicely explained

    Reply to this comment
  8. Fábio Pagoti

    Dec 24. 2013

    Hi IdioTechie!

    Congratulations for your post! There are many pages on google which seems to have such kind of information but yours is unique. You were the only to show code AND uml diagrams. Moreover the only one who focused on associations and other relationships between classes and interfaces. The rest just show visibility levels, attributes and methods :-(

    This content will be priceless for me as I’m developing a tool to transform ABAP code to UML diagrams using yUML.

    https://github.com/fabiopagoti/abap2yuml

    Thanks again and merry Xmas.

    Reply to this comment
    • IdioTechie

      Dec 25. 2013

      Thanks Fabio for your feedback. Appreciate it.
      Wish you the same and please keep visiting this website and provide your feedback for further improvements.

      Reply to this comment
  9. dhia

    Jan 02. 2014

    nice post..Tq

    Reply to this comment

Leave a Reply