Skip to content
Kevin Brightwell edited this page Aug 26, 2015 · 1 revision
Clone this wiki locally

A sample for traits application

Consider following Umple code for class S, C1, and C2.

namespace src;

class S {
	public void methodS() {
	System.out.println("methodS");
	}
}

class C1{
	isA S;
	public void method1() {
	System.out.println("method1");
	}	
}

class C2{
	isA S;
	public void method2() {
	System.out.println("method2");
	}
}

We are going to define a new class called C3 which is inherited from C2. On the other hand we want to have method1 from class C1. In Umple we don't have multi inheritance to be used for this situation and also multi inheritance has its own problems. There are two general solutions for this problem according to single inheritance:

Solution 1

This solution has the problem of duplicated code in method1. As Umple is a text-based modeling language so for large projects it is possible to have lots of duplicated code.

namespace src;

class S {
	public void methodS() {
	System.out.println("methodS");
	}
}

class C1{
	isA S;
	public void method1() {
	System.out.println("method1");
	}	
}

class C2{
	isA S;
	public void method2() {
	System.out.println("method2");
	}
}

class C3 {
	isA C2;
	
	public void method3() {
	System.out.println("method3");
	}	
	// here we have a duplication code for method 1.
	public void method1() {
	System.out.println("method2");
	}	
}

Solution 2

This solution doesn’t have the problem of duplicated code but two classes named S and C2 have been polluted by method1 that conceptually does not belong to them. Indeed, this solution has a conceptual problem.

namespace src;

class S {
	public void methodS() {
	System.out.println("methodS");
	}
	
	public void method1() {
	System.out.println("method1");
	}		
}

class C1{
	isA S;
}

class C2{
	isA S;
	public void method2() {
	System.out.println("method2");
	}
}

class C3 {
	isA C2;
	
	public void method3() {
	System.out.println("method3");
	}	
}

Solution 3

The solution is based on a new proposal for using trait in Umple.

namespace src;

class S {
	public void methodS() {
	System.out.println("methodS");
	}
}

trait T1 {
	public void method1() {
	System.out.println("method1");
	}		
}

class C1{
	isA S;
	isA T1; // this is trait composition
}

class C2{
	isA S;
	public void method2() {
	System.out.println("method2");
	}
}

class C3 {
	isA C2;
	isA T1; // this is trait composition
	public void method3() {
	System.out.println("method3");
	}	
}