Java – I can have different copies of static variables for each different type of inheritance class

I want the same static variable with different values, depending on the type of class

So I will

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
{

}

Then in my main program:

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 hope there is one for each type I want to inherit the static sprite variable and the drawing function of the drawing sprite But I don't want the genstealer elves to cover the ocean elves

Is that possible?

What should I do?

Solution

Using abstract methods:

public class Entity
{
     public abstract Bitmap getSprite();

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

public class Marine extends Entity
{
    public Bitmap getSprite() {
        return /*the sprite*/;
    }
}

If you like, the sprite returned by getsprite can be static About the benefits of this approach:

>You can't (easily) forget to include a sprite in your subclass because the compiler will complain if you don't implement abstract methods. > It's very flexible Suppose Marines should look different once they "upgrade" Just change marine's getsprite method to take this level into account. > This is the standard OO idiom for such things, so people who look at their code don't leave their minds

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>