我可以对已经初始化的变量(名称)使用 getter 和 setter 吗?它已在类级别初始化,因为值在许多方法中使用。
Class Family{
private String names[] = {"Arthur","Molly","Ginny","Fred", "George","Ron"};
// Is it ok to initialize this way since the names will be used in many methods.
private String surname;
public void displayOccupation(){
for(int o=0; o<occupation.length; o++){
System.out.println(names[o]+ "\t"+ occupation[o]+"\n");
}
}
public void displayNames(){
setSurname("Gates");
for(int x=0; x<names.length; x++){
System.out.println("\n"+rel[x]+"\t"+" = "+names[x]+" "+surname);
}
}
public String getSurname(){
return surname;
}
public void setSurname(String s){
surname=s;
}
}
还是我必须在每个访问私有变量的方法中重新初始化它?