img

Mixin-classes

The NTL+ language does not provide multiple inheritance features but sometimes it is necessary to implement identical code in several classes. In order to avoid repetitive code, it is recommended to use mixin-classes.

Mixin-classes allow declaring partial structure of a class that will consequently be included in other classes. Mixin-classes are not types, therefore it is forbidden to create instances of such classes.

To declare a mixin-class, it is necessary to add the keyword mixin before class, and specify any valid identifier after class that will be the name for a new class.

When a mixin-class is included in the declaration of another class, all properties and methods from a mixin-class are automatically transferred to the base class.

Example 1. Usage of a method from a mixin-class

 mixin class Mxn { datetime dt; void printTime() { System.Print(""+dt); } } class Cls : Mxn { void Method() { System.Print("Current time"); printTime(); // property 'dt' could also be used here as if it were declared in this class } } int Run() { Cls x; x.Method(); //Mxn a; - it is forbidden to create such an instance return(0); } 

Properties and methods that have already been declared in the base class will not be included again. Therefore, a mixin class may provide default implementation of methods that will be overridden in other classes that use the mixin-class.

Methods of a mixin-class will be compiled in the base class context, so that a mixin-class can operate at properties and methods of a base class as if these methods were declared in the base class itself.

Example 2. Overriding methods from a mixin-class

 mixin class Mxn { void X() { System.Print("Default implementation"); } void Y() { System.Print("time="+tm); // pay attention that 'tm' is not declared in 'Mxn' but it can be used here } } class Cls : Mxn { datetime tm; void X() { System.Print("Overriden behavior"); // this method will override the method in 'Mxn' class } } int Run() { Cls a; a.X(); a.Y(); return(0); } 

The class that is being created can use several mixin-classes, to do so the names of mixin-classes are specified separated by commas. It should be noted, if a derived class inherits from a base class and simultaneously uses mixin-class, then the methods of mixin-class override the methods of the base class, as if these methods were implemented in the derived class straightway. The behavior of classes is different if their names coincide. Properties of mixin-classes are not included in the derived class and the properties of the base class are used.

Example 3. Usage of inheritance and mixin-classes

 class BaseClass { int property = 1; void MethodA() { System.Print("Base class"); } } mixin class Mxn { int property = 2; void MethodA() { System.Print("Mixin class"); } } class Cls : BaseClass, Mxn { } int Run() { Cls a; a.MethodA(); // prints Mixin class System.Print("a.property="+a.property); // prints '1' return(0); }