我有一个班级Ship
public class Ship {
private String name;
private boolean loaded;
private int size;
private boolean bIsDefeated;
private int gunpower;
public Ship(int size, int gunpower, String name) {
this.size = size;
this.gunpower = gunpower;
this.name= name;
loaded = true;
bIsDefeated = false;
}
}
和Submarine
class Submarine extends Ship {
private final String NAME = "U-Boot";
private final int SIZE = 2;
private final int GUNPOWER = 1;
public Submarine(){
super(SIZE,GUNPOWER,NAME); //Here it gets underlined
}
}
有谁可以告诉我为什么那是不可能的?
答案 0 :(得分:2)
public UBoot(){
super(SIZE,GUNPOWER,NAME);
}
看起来你正在尝试创建一个名称与类不同的构造函数。试试static factory method
public static Submarine uboot() {
// something like
Submarine s = new Submarine(UBOAT_SIZE, UBOAT_GUNPOWER, "UBoat");
return s;
}
其中UBOAT_SIZE
和UBOAT_GUNPOWDER
是您班级中的private static final int
个变量
和Ship
的构造函数错误
this.bezeichnung = name;
应该是
this.name = name;
修改
好的,你现在已经改变了你的问题......
private final String NAME = "U-Boot";
private final int SIZE = 2;
private final int GUNPOWER = 1;
public Submarine(){
super(SIZE,GUNPOWER,NAME); //Here it gets underlined
}
SIZE
,GUNPOWDER
和NAME
都需要是private static final ...
变量,因为您在构造函数时没有Submarine的实例 - 所以它们必须是static
答案 1 :(得分:0)
将NAME
更改为static
class Submarine extends Ship {
private final static String NAME = "U-Boot";
private final static int SIZE = 2;
private final static int GUNPOWER = 1;
public Submarine() {
super(SIZE, GUNPOWER, NAME);
}
我认为你的构造函数名称是一个错字。
答案 2 :(得分:0)
您的潜艇构造函数错误
public UBoot(){
super(SIZE,GUNPOWER,NAME);
}
必须
public Submarine(){
super(SIZE,GUNPOWER,NAME);
}
指向NAME
变量的 更新应为static
答案 3 :(得分:0)
有几个问题:
没有UBoot
类,Submarine
:
public UBoot(){
super(SIZE,GUNPOWER,NAME);
}
应该是
public Submarine(){
super(SIZE,GUNPOWER,NAME);
}
和
没有名为bezeichnung
的字段。
此:
this.bezeichnung = name;
应该是:
this.name = name;
NAME
应为static
,所以:
private final String NAME = "U-Boot";
应该是:
private static final String NAME = "U-Boot";