本文介绍了Java默认构造函数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在查看一些代码,瞧:
I was looking over some code and voila:
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];
}
}
这是ELEVE类的唯一构造函数:
and this being the only constructor for class ELEVE:
public Eleve(String prenom, String nom) {
this.nom = nom;
this.prenom = prenom;
notes = new Note[200];
}
这到底如何工作?它使用30个对象(空值)实例化enfants数组.还有默认的构造函数吗?
Classe sixiemeA = new Classe("6eme A");
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");
推荐答案
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.
for (Eleve e : enfants) {
//Instantiate e here.
}
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.
这篇关于Java默认构造函数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!