Okay, so, for example, let's say I have an abstract class called "Vehicle". The Vehicle class, has, among other things, a static variable called wheels, which is not initialized. What I want to do is have other subclasses extending from the Vehicle class, like "Motorcycle", and "Truck", and in these subclasses, have the wheels initialized.
Code:
public abstract class Vehicle {
static int wheels; //number of wheels on the vehicle
}
But the below doesn't work:
public class Motorcycle extends Vehicle {
wheels = 2;
}
Is there a way to do this effectively?
EDIT: Thank you to all the people who replied so far. I get that making instances is probably a better way to go than to put them all in separate classes, but I don't get the "static" part of java perfectly, so I need a little help here.
What I'm trying to do for my program is have separate sprites for the Motorcycle and Truck classes, and I want them to be static so that I won't have to reload the image every time I create an instance of a Motorcycle or Truck. Other than that, though, they'll have almost identical properties to each other, which is why they'll both be extending from the Vehicle superclass.
The only other way I can see this being done is by just not declaring the sprite variable at the Vehicle class, but at the Motorcycle/Truck class, like below:
public abstract class Vehicle {
//Other coding
}
public class Motorcycle extends Vehicle {
static BufferedImage sprite = //initialize image
//Other coding
}
public class Truck extends Vehicle {
static BufferedImage sprite = //initialize image
//Other coding
}
If 'wheels' is static, there is only one and it will apply to all vehicles at the same time. So tricycle, a motorcycle, an 18-wheeler truck and a Ford will all have the same number of wheels.
That doesn't make sense to me. It would be better to have 'wheels' be an instance variable that is in the parent class but each subclass sets appropriately.
But you can try
Vehicle.wheels = 2;
NOTE: I'm adding to my answer since you added to your question.
I like your idea of having statics in each of the subclasses. But you should make them private. Then put an abstract method in the parent class (Vehicle) like
public abstract BufferedImage getSprite();
Then each direct subclass has to have the same method and it can return the private static variable.
Make the variable static so you only have to load them once. Make them private so that code outside the class itself can't fool with it and introduce bugs. You could make them 'final' if possible so the code in the class itself can't change it after the fact and introduce bugs. (A 'final' variable can't have its value changed but the contents of its value can change. So 'final' isn't a wonderful as it could be.)