cannot reference before supertype has been called java

3.7k Views Asked by At

I have a class 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;
    }
}

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

Can anyone tell me why that is not possible?

4

There are 4 best solutions below

0
On BEST ANSWER
public UBoot(){
   super(SIZE,GUNPOWER,NAME);
}

Looks like you're trying to make a constructor with a different name than the class. Try a static factory method

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

where UBOAT_SIZE and UBOAT_GUNPOWDER are private static final int variables in your class

and Ship's constructor is wrong

this.bezeichnung = name;

Should be

this.name = name;

EDIT

Okay you've changed your question now...

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, and NAME all need to be private static final ... variables because you don't have an instance of Submarine at the time of the constructor -- so they must be static

0
On

Change NAME to 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);
    }

I presume your constructor name issue was a typo.

2
On

Your submarine constructor is wrong

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

Must be

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

UPDATE as pointed NAME variable should be static

0
On

There are several problems:

There is no UBoot class but Submarine:

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

should be

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

and

there is no field named bezeichnung.

This:

this.bezeichnung = name;

should be:

this.name = name;

NAME should be static so this:

private final String NAME = "U-Boot";

should be:

private static final String NAME = "U-Boot";