Java Running A Constructor from a Subclass

68 views Asked by At

This is my class Mappa, it has mappaName as the main attribute of the constructor

public class Mappa {
    private Name mappaName;
    protected Settore [][] settore;
    private int Matrice [][];
    private static final int X=14;
    private static final int Y=23;
    public Mappa (Name mappaName){
        this.mappaName=mappaName;
        settore = new Settore[X][Y];
        for (int i=0; i < X; i++){
            for (int j=0; j<Y; j++) {
                settore[i][j] = new Settore (i,j);
            }
        }
        Matrice = new int[X][Y];
        if(mappaName==Name.FERMI){
            settore[8][10]=new Alieni(8,10);
            settore[9][10]=new Umani(9,10);
        }
        if(mappaName==Name.GALILEI||mappaName==Name.GALVANI){
            settore[5][10]=new Alieni(5,10);
            settore[7][10]=new Umani(7,10);
        }
    }
}

This is the subclass MappaFermi, which only runs the constructor of the class Mappa setting mappaName as Name.FERMI

public class MappaFermi extends Mappa {
    public MappaFermi() {
        super(null);
        new Mappa(Name.FERMI);
    }

Isn't new Mappa(Name.FERMI); supposed to set mappaName as Name.FERMI and because of the if condition setting settore[8][10]=new Alieni(8,10); and settore[9][10]=new Umani(9,10);? because when i make tests it returns null instead of the expected values.

public class MappaFermiTest {
    @Test
    public void testMappaFermiNome(){
        Mappa mappa = new MappaFermi();
        assertEquals(Name.FERMI, mappa.getMappaName());
    }
    @Test
    public void testMappaFermiAlieni(){
        Mappa mappa = new MappaFermi();
        assertEquals(Nome.ALIENI, mappa.getSettori()[8][10].getSettoreNome());
    }
}
1

There are 1 answers

1
Dragondraikk On

You seem slightly mistaken about what the new keyword does.

new calls a constructor and returns a new instance of the class. This means that your

public MappaFermi() {
    super(null);
    new Mappa(Name.FERMI);
}

actually creates a new Mappa object after calling super (which is the actual parent constructor call) and then discards it.

You actually wanted to do

public MappaFermi() {
    super(Name.FERMI);
}