Java — Initializing superclass variables in subclasses?

前端 未结 7 1547
逝去的感伤
逝去的感伤 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:51

    Maybe you'd like to think about the constructors you are using.

    public Vehicle(int wheels) {
        this.wheels = wheels; 
    }
    
    public Motorcycle(int wheels) {
        super(wheels);
    }
    
    public Motorcycle cycle = new Motorcycle(2);
    

    The Motorcycle uses the super constructor that knows what to do with the parameter. It automatically sets wheels to 2.

提交回复
热议问题