Java — Initializing superclass variables in subclasses?

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

    Static members are only defined once and are common to every extending class. Changing the value in one of them will affect all of the others. This is what I believe you really want to achieve:

    public abstract class Vehicle {
        private int _wheels; //number of wheels on the vehicle
        public int getWheels(){return _wheels;}
    
        protected Vehicle(int wheels){
            _wheels = wheels;
        }
    }
    
    public class Motorcycle extends Vehicle {
        public Motorcycle(){
            super(2);
        }
    }
    
    public class Car extends Vehicle {
        public Car(){
            super(4);
        }
    }
    

提交回复
热议问题