クラスの継承Constructor call must be the first statement in a constructor問題について
2993 ワード
親コード:
サブクラスコード:
テストクラス:
クラスの継承の問題では、サブクラスでsuperメソッド呼び出しによって親の属性を変更し、superが他のクラスの構築メソッドを呼び出す場合、superメソッドはサブクラスの構築メソッドにある必要があります.そうしないと、Constructor call must be the first statement in a constructorエラーが発生します.つまり、サブクラスがクラスのコンストラクタを呼び出す場合、super()文が最初の文になります.あるいは、自分のコンストラクタが自分の異なるパラメータコンストラクタを呼び出す場合、this()文は最初の文です.しかし、superメソッドはthisと同時に現れず、コンパイルにエラーが発生します.
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と同時に現れず、コンパイルにエラーが発生します.