views:

256

answers:

4

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?

A: 

So make one Sprite and give everyone instance variables. They are just references; hardly more than pointers.

DigitalRoss
+10  A: 

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.

Laurence Gonsalves
A: 
akf
Not override, but hide.
Totophil
A: 

It's not possible for it to be static in the super class. That static variable in the super class is shared (effectively a singleton) by all the sub classes. Anytime you change that (say, by instantiating a sub class), that change is reflected in all the other sub class instances.

Instead, make the sprite static in the subclasses, and then use the method structure described by Laurence.

Carl