Tom Auger
Tom Auger

Reputation: 20091

Override parent class instance variable in subclass

In PHP it's trivial to override properties of a class in a subclass. For instance:

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

   //... 
}

class Boss_Enemy extends Generic Enemy {
    protected $hp = 1000;
    protected $str = 25;
}

Which is extremely convenient because at-a-glance you can see in what ways the subclass differs from the parent class.

In AS3 the only way I've found is through getters, which really isn't elegant at all:

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;
   }
}

Is there a nicer way of doing this that aligns with the PHP approach?

Specifically: let's say I'm writing an API that will let a developer easily spin off his own Enemies. I would rather document that you just have to override hp and str properties rather than explain that they have to create a new getter for each property they wish to override. It's a matter of trying to create the cleanest API and the easiest to document and maintain.

Upvotes: 1

Views: 276

Answers (1)

Tom Auger
Tom Auger

Reputation: 20091

Sometimes ya just have to write the SO question in order to see the (obvious) answer:

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

Upvotes: 2

Related Questions