tech

[English] [Japanese]

17. Interface

LuneScript does not support multiple inheritance of classes, but does support interfaces.

interface

If you've used Java or C#, you'll be familiar with it, but you can think of an interface as a class with limited functionality.

Specifically, interfaces differ from classes in the following ways:

  • The declaration is an interface, not a class.
  • has no members.
  • All methods are abstract. Therefore, an interface cannot be instantiated by itself.
  • A class that implements an interface has () in its extend
  • A class can implement multiple interfaces
  • Don't put override on the method of the class that implements the interface.

Here is an example interface:

// @lnsFront: ok
interface IF {
   pub fn func();
}
class Test extend (IF) {
   pub fn func() {
      print( __func__ );
   }
}
fn sub( obj:IF ) {
   obj.func();
}
sub( new Test() ); // Test.func

This example defines an interface IF.

Here is an example class that implements two interfaces:

// @lnsFront: ok
interface IF1 {
   pub fn func1();
}
interface IF2 {
   pub fn func2();
}
class Test extend (IF1,IF2) {
   pub fn func1() {
      print( __func__ );
   }
   pub fn func2() {
      print( __func__ );
   }
}
fn sub( obj1:IF1, obj2:IF2 ) {
   obj1.func1();
   obj2.func2();
}
let mut test = new Test();
sub( test, test ); // Test.func Test.func2

If you implement multiple interfaces, declare them in () after extend .

By the way, as a restriction when implementing multiple interfaces, an error will occur if there are methods with the same name but different types in the interface to be implemented as follows.

// @lnsFront: error
interface IF1 {
   pub fn func():int;
}
interface IF2 {
   pub fn func():str;
}
class Test extend (IF1,IF2) { // mismatch IF1.func, IF2.func
}

Note that default processing of methods is not supported as a specification of the current interface.

summary

LuneScript does not support multiple inheritance of classes, but does support interfaces.

Next time, we will explain Mapping.