A trait is a construct that lets you use code again and again. In a language that does not let classes inherit from more than one parent class, such as ViviFire, traits can decrease some of the limits this causes. Traits let you use sets of methods freely in different classes, related or not. The effects of the mixture of traits and classes are specified in a manner which is easy to accept.
A trait shows almost the same as a class, but specifies only behavior in a controlled manner. You cannot make a variable from a trait. Together with the usual inheritance construct, traits do what is known as horizontal composition of behavior. That is, the trait applies its methods to a class without inheritance.
Declaration of traits
A trait usually starts with
Trait and completes with
Between these two lines you can put one or more permitted statements:
Sub, and TBD.
A class that uses a trait has access only to the public members of the trait—methods and properties. These also become part of the interface of the class . The class cannot directly get access to the other members of the trait.
A method or property is usually made with a body of statements.
But if you use the modifier
@Abstract, then the method or property cannot have a body.
A class that uses the trait must declare the method or property again, and supply a body of statements.
If a class and a trait make available different methods with the same signature, then the class comes before the trait. And if a trait and a parent class cause the same problem, then the trait comes before the parent class.
That is, class > trait > parent class.
Trait A Method Calculate ' ... End Method End Trait Trait B Method Calculate ' ... End Method End Trait Class Calculator Does A Does B Method CalculateA Does A.Calculate Method CalculateB Does B.Calculate End Class
To Change method visibility
Trait Foobar Method Foo ' ... End Method Method Bar ' ... End Method End Trait Class Barless Does Foobar Function Bar Does Foobar.Bar End Class
Traits composed from traits
Trait Foo Method Foo ' ... End Method End Trait Trait Bar Method Bar ' ... End Method End Trait Trait Foobar Does Foo Does Bar ' ... End Trait
If all of the methods and properties of a trait must be abstract, then you can put
@Abstract before the trait.
Then it is not necessary to put the modifier before each method and property.
An abstract trait has more limits than a usual trait:
- It must have one or more public procedures (
- It must not have private procedures (
Shared trait members
Uses for traits
@Abstract Class Pet End Class Trait Walk Method StartWalking End Method End Trait Trait Swim Method StartSwimming End Method End Trait @Abstract Trait Speak Method Speak As String End Trait Class Dog Is Pet Does Walk Does Swim Does Speak @Override Method Speak As String Return "Arf" End Method End Class Class Cat Is Pet Does Walk Does Speak @Override Method Speak As String Return "Meow" End Method End Class Class Fish Is Pet Does Swim End Class