when a class implements an interface, do the interface variables need to be re-declared?

240 Views Asked by At

In the Haxe manual we see an example where the interface contains 2 variables but the class that implements the interface also declares those variables:

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() { }
}

Was it necessary to do so?

1

There are 1 best solutions below

0
On BEST ANSWER

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.

Sounds very much like yes to me. Anyway, let's just give it a try:

package ;

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

class One implements Placeable {
  public var x:Float;
  public var y:Float;
  public function new() { }
}

class Two implements Placeable {
  public var x:Float;
  public function new() { }
}

class Main
{

    public function new() 
    {
        var one : Placeable = new One();
        var two : Placeable = new Two();
    }

}

yields

Building SomeTest
haxe  -cp . -cpp bin/Test -main Main
./Main.hx:14: lines 14-17 : Field y needed by Placeable is missing
Build halted with errors (haxe.exe).
Done(1)

Bottom line: Yes, they have to be redeclared.