Why are Getter and Setter better than directly changing and retrieving fields ?<br /> <br /> or <br /> <br /> What is the significance of variable hiding in Java ?<br /> <br /> or <br /> <br /> Why it's preferred to keep variables private and allow their access through getter and setter methods ?
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Interview Questions and Answers

 Q1. Why are Getter and Setter better than directly changing and retrieving fields ?

or

What is the significance of variable hiding in Java ?

or

Why it's preferred to keep variables private and allow their access through getter and setter methods ?
Core Java
Ans. 1. Methods can participate in runtime polymorphism whereas member variables cannot.

For example -

Vehicle vehicle = new Car();

car.getObjVariable();// will return variable defined in Car

whereas

car.variable

will return the variable from Car class irrespective of the object it holds.

2. Validations can be performed before setting the variables.

3. If the input format changes or some other value or calculated value needs to be returned , that can be absorbed by making change ( wrapping ) in the setter and getter. By this the call to method from outside or interface to the object will remain the same.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   beans   getter   setter


Related Questions

  How to generate getters and setters automatically in eclipse ?
 Why it's a good practice to expose member elements through getter methods ?
  What ate the getter and setter methods ?
 Are getters setter / accessor mutator methods instance methods or static methods ? why ?



Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: