Click here to Skip to main content
16,018,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was looking over some code and voila:

C#
public class Classe {
    private String nomClasse;
    private Eleve[] enfants;
    private int nrEnfants = 0;
    private String[] matieres;
    private int nrMatieres = 0;

    public Classe(String nomClasse) {
        this.nomClasse = nomClasse;
        enfants = new Eleve[30];
        matieres = new String[10];
    }
}

and this being the only constructor for class ELEVE:
C#
public Eleve(String prenom, String nom) {
        this.nom = nom;
        this.prenom = prenom;
        notes = new Note[200];
    }



How on earth does this work? It instantiates the enfants array with 30 objects (null values). Is there still a default constructor?

Classe sixiemeA = new Classe("6eme A");
Posted

The line:
Java
enfants = new Eleve[30];

only initializes the array. It does not initialize the objects within the array. You have to do it yourself by iterating the array instantiating each element of the array.
Java
for (Eleve e : enfants) {
      //Instantiate e here.
}
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 25-Aug-11 17:22pm    
Proposed as the solution! 5+
Sergey Alexandrovich Kryukov 25-Aug-11 23:30pm    
Agree, a 5.
--SA
When you specify a new constructor then you lose the default constructor that you originally had. The only way to get a default constructor back is to make a new one that takes no parameters. Eg


Java
public Classe(){
   // define some code in here to initialize the variables that you've created
   enfants = new Eleve[30];
   // you can also go on to add things to the array after this like shameel said
   // you can use a loop or assign to the positions directly Eg
   enfants[0] = new Eleve("enfant1","1");
   // or using a loop to add values to the empty array :
   for(int i = 0; i < enfants.length; i++)
   {
      // this will go through the array and add a new instance of Eleve at each
      // level.
      enfants[i] = new Eleve("enfant" + i.ToString(), i.ToString());
   }
}


hope this helps.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900