Search code examples
javainheritancestatic-variables

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


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 static Bitmap sprite;

     public void draw(Canvas canvas, int x, int y)
     {
          canvas.drawBitmap(sprite, x, y, null);
     }
}

public class Marine extends Entity
{

}

public class Genestealer extends Entity
{

}

And then in my main program go:

Marine.sprite = // Load sprite for all instances of Marine
Genestealer.sprite = // Load sprite for all instances of Genestealer

I don't want to store the same sprite in every instance of the class. I want one for each type of class. I want to inherit the static sprite variable and the draw function which will draw the sprite. But I don't want the Genstealer sprite to override the Marine sprite.

Is this possible?

How would I do it?


Solution

  • 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.