类中的虚方法

时间:2012-07-05 05:39:35

标签: oop haxe

我正在尝试创建一个简单的可扩展类,然后扩展它,然后将扩展类的实例放入一个变量中,然后调用扩展类覆盖方法。在其他语言中,这被称为虚拟方法。我无法在Haxe找到任何关于此的信息。

class Shape
{
    public virtual function DrawShape(): Void {}
}

class Triangle extends Shape
{
    public virtual function DrawShape(): Void { printf("Triangle"); }
}

class Square extends Shape
{
    public virtual function DrawShape(): Void { printf("Square"); }
}


//usage
var myShape : Shape;

//As Triangle
myShape = new Triangle();
myShape.DrawShape(); //outputs Triangle, even though it is type Shape variable

//As Square
myShape = new Square();
myShape.DrawShape(); //outputs Square, even though it is type Shape variable

所以,如果有人知道如何在Haxe这样做,请帮忙。感谢。

2 个答案:

答案 0 :(得分:2)

virtual ==覆盖Haxe语言

答案 1 :(得分:0)

尝试

interface IShape
{
  function drawShape () : Void;
}

class Tri implements IShape
{
  public function drawShape () : Void { return "Tri"; }
}

class Square implements IShape
{
  public function drawShape () : Void { return "Square"; }
}