tech

[English] [Japanese]

14. Class Inheritance

LuneScript supports class inheritance.

class inheritance

Here is an example of class inheritance:

// @lnsFront: ok
class Super {
   pub fn func() {
      print( __func__ );
   }
}
class Sub extend Super {
}
let sub = new Sub();
sub.func(); // Super.func

This is an example of a Super class being inherited by a Sub class.

Inheritance specifies the parent class to inherit from using extend when declaring the class.

Only one class can be inherited.

Note that if the constructor access control is pri, the class cannot be inherited.

subclass constructor

A subclass must declare a constructor if the parent class constructor has arguments.

For example, in the following example, the Super class does not explicitly declare a constructor, but internally a default constructor is generated with arguments that initialize the member val.

// @lnsFront: ok
class Super {
   pro let val:int;
}
class Sub extend Super {
   pub fn __init( val:int ){
      super( val );
   }
   pub fn func() {
      print( self.val );
   }
}
let sub = new Sub( 1 );
sub.func(); // 1

In this case, the Sub class that inherits from Super must declare a constructor for the Sub class because the parent class has a constructor with arguments. It also calls super() to execute the constructor of the parent class Super inside the constructor of the Sub class. This super() should be written on the first line.

Prohibition of class inheritance

Declare it final if you want to suppress the inheritance of the class.

The following declares the Super class final, so a Sub class that inherits from the Super class will error.

// @lnsFront: error
final class Super {
}
class Sub extend Super { // error
}

summary

LuneScript supports class inheritance with the following specifications:

  • Only one class can be inherited
  • Subclasses must call the parent class constructor.
  • Constructor call of parent class is done in super().
  • super() should each be on the first line of the constructor.

Next time, we'll talk about method overriding.