2.2.3 Interfaces

An interface can be understood as the signature of a class because it describes the public fields of a class. Interfaces do not provide implementations, but rather offer purely structural information:

interface Printable {
    public function toString():String;
}

The syntax is similar to classes, with the following exceptions:

  • The interface keyword is used instead of the class keyword.
  • Functions do not have any expressions.
  • Every field must have an explicit type.

Interfaces, unlike structural subtyping, describe a static relation between classes. A given class is only considered to be compatible to an interface if it explicitly states as much:

class Point implements Printable { }

Here, the implements keyword denotes that Point has an "is-a" relationship with Printable, i.e. each instance of Point is also an instance of Printable. While a class may only have one parent class, it may implement multiple interfaces through multiple implements keywords:

class Point implements Printable
  implements Serializable

The compiler checks if the implements assumption holds. That is, it makes sure the class actually does implement all the fields required by the interface. A field is considered implemented if the class or any of its parent classes provide an implementation.

Interface fields are not limited to methods. They can be variables and properties as well:

interface Placeable {
  public var x:Float;
  public var y:Float;
}

class Main implements Placeable {
  public var x:Float;
  public var y:Float;

  static public function main() {}
}

Interfaces can extend multiple other interfaces using the extends keyword:

interface Debuggable extends Printable extends Serializable
since Haxe 4.0.0

Like classes, interfaces can be marked with the final keyword, preventing them from being extended.

Trivia: Implements Syntax

Haxe versions prior to 3.0 required multiple implements keywords to be separated by a comma. We decided to adhere to the de-facto standard of Java and got rid of the comma. This was one of the breaking changes between Haxe 2 and 3.