uOttawaUniversity of Ottawa - Canadas University
list of dots

Umple User Manual    [Previous]   [Next]   



A trait is a partial description of a class that can be reused in several different classes.

To have a class include the content of a trait, you use the 'isA' directive, in the same manner as specifying a superclass, or an implemented interface. Traits should therefore be named to be consistent with this. For example, if you wanted to include in several classes the notion of having a colour, and some methods to manipulate the colour, you could create a trait called Colourable. The classes to be colourable would include 'isA Colourable;'. This is very similar to the way interfaces and inheritance are defined; the difference is that virtually any model or code elements can be in a trait, and they will be 'copied' into each class.

Traits can be used in place of standard inheritance where there is already a superclass, since multiple inheritance isn't allowed in Umple to be consistent with Java and several other languages. Traits can be used to inject attributes, associations, state machines, constraints, methods and many other elements. They are one of several approaches in Umple to separation of concerns; the others are the mixin ability (ability to specify a class several times and have the elements added together), and the aspect oriented capabilities. Note that traits themselves are subject to being mixed in; you can declare two parts of the same trait in two different places in an Umple system.

Traits are not part of UML. A UML class diagram drawn from an Umple file containing traits will 'flatten' the traits. The trait elements will appear in all classes that include that trait. In the first example below, the name and address attribute will appear in the class diagram of both Person and Company.


// Example of use of a trait in Umple
// The trait has regular attributes, derived attribute
// and a method that are copied into Organization
// and Company
trait Identifiable {
  fullName = {firstName + " " + lastName}
  Boolean isLongName() {return lastName.length() > 1;}  

class Person {
  isA Identifiable;

class Organization {
  Integer registrationNumber;

class Company {
  isA Organization, Identifiable;

Load the above code into UmpleOnline



traitDefinition : trait [name] [[traitParameters]]? { [[traitContent]]* }

traitContent- : [[requiredModelElements]]
    | [[comment]]
    | [[traitDefinition]]
    | [[trace]]
    | [[position]]
    | [[displayColor]]
    | [[abstract]]
    | [[keyDefinition]]
    | [[softwarePattern]]
    | [[depend]]
    | [[symmetricReflexiveAssociation]]
    | [[attribute]]
    | [[stateMachine]]
    | [[inlineAssociation]]
    | [[concreteMethodDeclaration]]
    | [[abstractMethodDeclaration]]
    | [[constantDeclaration]]
    | [[invariant]]
    | ;
    | [[exception]]
    | [[extraCode]]