在超类型被称为java之前无法引用

时间:2015-06-17 14:51:24

标签: java constructor instance

我有一个班级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
    }
}

有谁可以告诉我为什么那是不可能的?

4 个答案:

答案 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_SIZEUBOAT_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
}

SIZEGUNPOWDERNAME都需要是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";