简体   繁体   中英

can i use getters and setters to already initialized variable?

Can i use getters and setters to a already initialized variable (names)? it has been initialized in class level as the values are used in many method.

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;
}
}

Or do i have to re initialize it in every method that access the private variable ?

with the help of setter methods private variable of can be initialized. there is no need to initialized it in every method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM