Java — Initializing superclass variables in subclasses?

前端 未结 7 1526
逝去的感伤
逝去的感伤 2020-12-19 04:18

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 init

相关标签:
7条回答
  • 2020-12-19 04:52

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

    0 讨论(0)
提交回复
热议问题