无法弄清楚为什么我收到此错误。在记事本中工作,通过cmd运行javac(显然更多的是文件)。如果你需要我链接更多我可以。 我的错误发生在“setCruiseShip”,我试图将当前链接到超类。 错误:调用super必须是构造函数中的第一个语句。
class Ship
{ protected String name;
protected float speed;
protected int year;
public Ship() {name=""; speed=year=0;}
public Ship(String n, float sp, int y) {name=n; speed=sp; year=y;}
public String getName() {return name;}
public float getSpeed() {return speed;}
public int getYear() {return year;}
public void setShip(String n, float sp, int y) {name=n; speed=sp; year=y;}
public String toString() {return "Ship named "+name+ " with max speed of "
+speed+ " was built in " +year;}
}
class CruiseShip extends Ship
{ protected int maxpass;
public CruiseShip() {super(); maxpass=0;}
public CruiseShip(String n, float sp, int y, int mp) {super(n, sp, y);
maxpass=mp;}
public int setMaxpass(int mp) {maxpass=mp;}
public void setCruiseShip(String n, float sp, int y, int mp){super(n,sp,y);
maxxpass=mp;}
public String toString() { return super.toString() +" carries "
+maxpass+ " passengers";}
}
答案 0 :(得分:1)
class Ship
没有名为setCruiseShip
的方法。你可能想要的是调用setShip
方法。取代
super(n,sp,y);
与
setShip(n,sp,y);
答案 1 :(得分:0)
只能从子类的构造函数(而不是从任何方法)调用超级构造函数。修改和编译的程序如下所示
class Ship {
protected String name;
protected float speed;
protected int year;
public Ship() {
name = "";
speed = year = 0;
}
public Ship(String n, float sp, int y) {
name = n;
speed = sp;
year = y;
}
public String getName() {
return name;
}
public float getSpeed() {
return speed;
}
public int getYear() {
return year;
}
public void setShip(String n, float sp, int y) {
name = n;
speed = sp;
year = y;
}
public String toString() {
return "Ship named " + name + " with max speed of " + speed
+ " was built in " + year;
}
}
class CruiseShip extends Ship {
protected int maxpass;
public CruiseShip() {
super();
maxpass = 0;
}
public CruiseShip(String n, float sp, int y, int mp) {
super(n, sp, y);
maxpass = mp;
}
public int setMaxpass(int mp) {
maxpass = mp;
}
public void setCruiseShip(String n, float sp, int y, int mp) {
setShip(n, sp, y);
maxpass = mp;
}
public String toString() {
return super.toString() + " carries " + maxpass + " passengers";
}
}
答案 2 :(得分:0)
super(somevalues...)
。 Java不允许从方法中调用super(somevalues...)
。此外,当您在子类中定义构造函数时,其第一个语句应该是super()/super(somevalues)
构造函数或this(somevalues...)
。如果你不这样做,那么编译器会隐式添加默认的no-arg超级构造函数。
this()
表示构造函数重载
而且给定的事实是
public void setCruiseShip(String n, float sp, int y, int mp){super(n,sp,y);
不是子类中的构造函数。
构造函数definition
是,构造函数名称必须(我不是说'应该')与没有返回类型的类名相同,并且允许任何访问修饰符(如private,default,protected,public)。< / p>
因此setCruiseShip
与CruiseShip