0

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 ?

2
  • 4
    Yes. In fact, that's most of the point of setters and getters. Commented Oct 28, 2013 at 17:08
  • 1
    “re-initialize it in every method” makes no sense at all. Why would you ever want to have a variable if you overwrite it before any access? Commented Oct 28, 2013 at 17:44

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.