Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Actionscript 3 重写子类中的父类实例变量_Actionscript 3_Properties_Overriding - Fatal编程技术网

Actionscript 3 重写子类中的父类实例变量

Actionscript 3 重写子类中的父类实例变量,actionscript-3,properties,overriding,Actionscript 3,Properties,Overriding,在PHP中,在子类中重写类的属性很简单。例如: class Generic_Enemy { protected $hp = 100; protected $str = 5; //... } class Boss_Enemy extends Generic Enemy { protected $hp = 1000; protected $str = 25; } 这非常方便,因为您一眼就能看出子类与父类在哪些方面不同 在AS3中,我找到的唯一方法是通过get

在PHP中,在子类中重写类的属性很简单。例如:

class Generic_Enemy {
   protected $hp = 100;
   protected $str = 5;

   //... 
}

class Boss_Enemy extends Generic Enemy {
    protected $hp = 1000;
    protected $str = 25;
}
这非常方便,因为您一眼就能看出子类与父类在哪些方面不同

在AS3中,我找到的唯一方法是通过getter,这一点都不优雅:

public class GenericEnemy {
   private var _hp:uint = 100;
   private var _str:uint = 25;

   public function get hp():uint {
      return _hp;
   }

   public function get str():uint {
      return _str;
   }
}

public class BossEnemy extends GenericEnemy {
   override public function get hp():uint {
      return 1000;
   }

   override public function get str():uint {
      return 25;
   }
}
有没有更好的方法与PHP方法保持一致


具体来说:假设我正在编写一个API,它可以让开发人员轻松摆脱自己的敌人。我宁愿记录您只需要重写hp和str属性,而不是解释它们必须为它们希望重写的每个属性创建一个新的getter。这是一个试图创建最干净、最易于记录和维护的API的问题。

有时候你只需要写一个SO问题,就可以看到(显而易见的)答案:


是的,你明白了。尽管你可能想在做其他事情之前先打电话给super。否则,如果在超类构造函数中设置值,它们最终将覆盖在子类中设置的值。在AS3中,您可以省略对super的调用,它将在运行子类构造函数之前自动调用它。@Cadin,我在子类方法的末尾显式调用super(),以防父类构造函数对变量做了一些操作,只是为了使代码更具可移植性。
public class GenericEnemy {
   protected var _hp:uint = 100;
   protected var _str:uint = 25;

   public function GenericEnemy(){
     //...
   }
}

public class BossEnemy extends GenericEnemy {
   public function BossEnemy(){
      _hp = 1000;
      _str = 50;

      super();
   }
}