Java Atribute In Class and Subclass

84 views Asked by At

I have the class Mappa with a subclass MappaFermi and an attribute mappaName (to choose from an Enum).

I am trying to write a test whith the constructor MappaFermi() but i can't seem to write it correctly.

public class Mappa {
    private Name mappaName;
    public Mappa (Name mappaName){
        this.mappaName=mappaName;
        ...

    }
}

public class MappaFermi extends Mappa {
    public MappaFermi(Name mappaName) {
        super(mappaName);
        }
    }

public enum Name {
 FERMI, GALILEI, GALVANI
}   

I have tried all the suggestions given by eclipse but still get an error.

    public class MappaFermiTest {
        @Test
            public void testMappaFermi() {
                Mappa mappa = new MappaFermi(Name.FERMI);
                assertNotNull(mappa);
            }

 @Test
            public void testMappaFermi() {
                Mappa mappa = new MappaFermi();
                assertNotNull(mappa);
            }
    }
2

There are 2 answers

0
tobias_k On BEST ANSWER

If you want to use new MappaFermi(), you have to define a no-argument constructor. This is the default constructor, and any class that has no other constructor will implicitly have a no-arg constructor. But as soon as you define a constructor with arguments, like Mappa(Name mappaName), the no-arg default constructor is no longer available and has to be explicitly defined.

public MappaFermi() {
    super(null); // or whatever is a good 'default' name
}

Also, testing assertNotNull(mappa); right after Mappa mappa = new MappaFermi(whatever); is pretty pointless, as there is no way it could be null at this point.

0
M__ On

A few mistakes here:

-Three methods with the same name testMappaFermi.
The tests can be done all in one method, or you can rename the methods if you really want three methods.

-The second test is not written correctly. What would work:

Name mappaName = Name.FERMI;
Mappa mappa = new MappaFermi(mappaName);

-The third test uses new MappaFermi() without a no-argument constructor being defined.
Either you want to put an argument inside the constructor, or write a no-argument constructor as so :

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