Can I have different copies of a static variable for each different type of inheriting class

后端 未结 5 1394
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 16:49

I want to have the same static variable with a different value depending on the type of class.

So I would have

public class Entity
{
     public stat         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 17:10

    Use an abstract method:

    public class Entity
    {
         public abstract Bitmap getSprite();
    
         public void draw(Canvas canvas, int x, int y)
         {
              canvas.drawBitmap(getSprite(), x, y, null);
         }
    }
    
    public class Marine extends Entity
    {
        public Bitmap getSprite() {
            return /*the sprite*/;
        }
    }
    

    The sprite returned by getSprite can be a static if you like. Nice things about this approach:

    • You can't (easily) forget to include a sprite in your subclass, since the compiler will complain if you don't implement the abstract method.

    • It's flexible. Suppose a Marine should look different once he "levels up". Just change Marine's getSprite method to take the level into account.

    • It's the standard OO-idiom for this sort of thing, so people looking at their code won't be left scratching their heads.

提交回复
热议问题