tech

[English] [Japanese]

16. Class override

LuneScript supports method overrides.

method override

All methods of a class can be overridden.

Rather, overrides cannot currently be suppressed.

Here's an example method override:

// @lnsFront: ok
class Super {
   pub fn func() {
      print( __func__ );
   }
}
class Sub extend Super {
   pub override fn func() {
      print( __func__ );
   }
}
fn test( obj:Super ) {
   obj.func();
}
test( new Super() ); // Super.func
test( new Sub() ); // Sub.func

Here, the Sub class overrides the func method of the Super class.

Methods on the Sub class side to be overridden must be specified with the override keyword.

Parent class method call

Use super() to call a parent class method from an overriding subclass.

Here is an example for super():

// @lnsFront: ok
class Super {
   pub fn func(): int {
      return 1;
   }
}
class Sub extend Super {
   pub override fn func(): int {
      return 10 + super();
   }
}
fn test( obj:Super ) {
   print( obj.func() );
}
test( new Sub() ); // 11

In this example, the Super class's func() method is overridden by a Sub class. And we are using func() through super() in the Sub class to call the func() method in the Super class.

abstract

You can define abstract methods with no entity.

Here is an abstract example:

// @lnsFront: ok
abstract class Super {
   pub abstract fn func(): int;
}
class Sub extend Super {
   pub override fn func(): int {
      return 10;
   }
}
fn test( obj:Super ) {
   print( obj.func() );
}
test( new Sub() );

In this example, the func() method is an abstract method with no substance.

Note that classes with abstract methods must be declared as abstract classes.

The entity of an abstract method is defined in the inherited class. If the inherited class does not override all abstract methods of the parent class, the inherited class must be declared as abstract.

An abstract class cannot be instantiated by itself.

summary

The specification of the LuneScript method override/abstract is as follows.

  • All methods can be overridden
  • An overriding class must explicitly specify the override
  • Use super() to call the original method of override from the overriding method.
  • You can declare abstract methods with no entity
  • A class with abstract methods is an abstract class
  • abstract methods must be overridden in subclasses
  • An abstract class cannot be instantiated by itself

Next time, I will explain about advertise of class.