在调用超类型之前无法引用 java

cannot reference before supertype has been called java

我有一个classShip

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
    }
}

谁能告诉我为什么那不可能?

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);
    }

我认为您的构造函数名称问题是一个拼写错误。

你的潜艇构造函数是错误的

public UBoot(){
    super(SIZE,GUNPOWER,NAME);
}

必须

public Submarine(){
    super(SIZE,GUNPOWER,NAME);
}

UPDATE 指出 NAME 变量应该是 static

public UBoot(){
   super(SIZE,GUNPOWER,NAME);
}

看起来您正在尝试创建一个名称与 class 不同的构造函数。试试 static factory method

public static Submarine uboot() {
    // something like
    Submarine s = new Submarine(UBOAT_SIZE, UBOAT_GUNPOWER, "UBoat");
    return s;
}

其中 UBOAT_SIZEUBOAT_GUNPOWDER 是您 class

中的 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
}

SIZEGUNPOWDERNAME 都需要是 private static final ... 变量,因为在构造函数时您没有 Submarine 的实例 - - 所以他们必须是 static

存在几个问题:

没有UBootclass但是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";