关于类的继承Constructor call must be the first statement in a constructor问题

父类代码:

public class Bicycle {
    public int cadence;
    private int gear;
    private int speed;
    public  Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
        System.out.println("The parameterize constructor of bicycle is called.");
    }

    public void setCadence(int newValue) {
        cadence = newValue;
    }

    public void setGear(int newValue) {
        gear = newValue;
    }


}

子类代码:

public class MoutainBike extends Bicycle{
    private int seatHight;

    public  MoutainBike(int startHeight,int startCadence,int startSpeed,int startGear){
        super(startCadence,startSpeed,startGear);
        seatHight=startHeight;
        System.out.println("The MountainBike constructor of bcycle is called.");
    }
}

测试类:

public static void main(String[] args) {
        MoutainBike monutainBike=new MoutainBike(4,9,1,2);

    }

对于类的继承问题,在子类中通过super方法调用修改父类的属性,在super调用其他类的构造方法时,super方法必须在子类的构造方法中,否则将会出现Constructor call must be the first statement in a constructor错误,也就是说:在子类调用类的构造器时,super() 语句要是第一条语句;或者自己的构造器调用自己的不同参数构造器时,this()语句要是第一条语句。但是还有一点,super方法不能和this同时出现,编译会出现错误。

你可能感兴趣的:(java)