I have this class that everytime I call the constructor should increment the id
public class Candidato {
private String nome;
private String cognome;
private final int id; // id that tracks number of objects
private static int counter=0; //counter that increments the id
private static int counterd=0;
private static int counters=0;
private static int counterp=0;
private double voti;
private int doc;
private int stud;
private int pta;
public Candidato(String n,String c){
this.id=counter++; //everytime i call the constructor increment me
this.nome=n;
this.cognome=c;
System.out.println(counter+"- -"); // here
}
public int getNumero(){
//System.out.println(id+"--id--");
return id+1;
}
}
So my doubts arrise here : Suppose I got a class Elections that calls the Candidato constructor, how can i keep track of the Candidato id everytime a new instance of elections gets created ?
Like in this example at testNumeriCandiati() i get some strange numbers as they are not the expected ones, therefore everytime I create an Election class I want to set the Candidato id back to 0
public class TestR2_Candidati extends TestCase {
public void testCandidato(){
Elezione sistema = new Elezione();
Candidato c = sistema.nuovoCandidato("Marco", "Gilli");
assertNotNull("metodo nuovoCandidato() non implemenato",c);
assertEquals("Marco",c.getNome());
assertEquals("Gilli",c.getCognome());
assertEquals(1,c.getNumero());
}
public void testGetCandidato(){
Elezione sistema = new Elezione();
Candidato c = sistema.nuovoCandidato("Marco", "Gilli");
Candidato cc = sistema.getCandidato(1);
assertNotNull("metodo getCandidato() non implemenato",cc);
assertSame("Non viene restituito lo stesso candidato",c,cc);
}
public void testNumeriCandiati(){
Elezione sistema = new Elezione();
Candidato c1 = sistema.nuovoCandidato("Marco", "Gilli");
Candidato c2 = sistema.nuovoCandidato("Francesco", "Profumo");
Candidato c3 = sistema.nuovoCandidato("Rodolfo", "Zich");
assertEquals("Non corrisponde il numero",1,c1.getNumero());
assertEquals("Non corrisponde il numero",2,c2.getNumero());
assertEquals("Non corrisponde il numero",3,c3.getNumero());
}
}
Your counter is stored as a static variable of
Candidato, so its value does not depend on creation of instances ofElezione. If you want this funcionality you need to manage the counter ofCandidatointoElezione: