list of dots

User Manual    [Previous]   [Next]   

RE001 Violation of Immutability

Umple runtime exception thrown when Immutability is violated in a constructor

The immutable keyword in Umple can be applied to a class, an attribute or an association to ensure that they can only be set in the constructor, and cannot be modified again subsequently. The immutability of associations means that all associated objects must be specified as unique constructor arguments. Violation of this is detected by the constructor, in which case a RuntimeException is thrown. This can be caught by a try-catch block.

In the example below, an immutable Path has immutable pathElements (instances of Point2D). The Path instances are of an immutable class too (here Point2D), and the only way to construct this association is in arguments to the constructor. But it is necessary to avoid duplicate objects in the constructor and a runtime exception is thrown when this constraint is violated. So, a runtime exception is thrown here when an attempt is made to create a Path with duplicate instances of Point2D.


// This demonstrates code that will throw the
// immutability exception  
class Point2D  
  Float x;  
  Float y;  

class Path  
  1 -> * Point2D pathElements;  
    public static void main(String[] argv) {
      Point2D p2d = new Point2D(0,0);

      // This will throw an exception since the
      // pathElements cannot be duplicate
      try {
        Path p = new Path(p2d,p2d);
      catch (RuntimeException re) {
        System.out.println("Exception Caught: "+re+"\n");    


Load the above code into UmpleOnline