Java - Interview Questions and Answers on Getter and Setter

Q1.  What ate the getter and setter methods ?

Ans. getters and setters methods are used to store and manipulate the private variables in java beans. A getters as it has name, suggest retrieves the attribute of the same name. A setters are allows you to set the values of the attributes.

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

Ans. 1. Methods can participate in runtime polymorphism whereas member variables cannot.

2. Validations can be performed before setting the variables.

3. If the input format changes , that can be absorbed by making change ( wrapping ) in the setter and getter.

Q3.  How to generate getters and setters automatically in eclipse ?

Ans. Right Click -> Source -> Generate Getters and Setters.

and it will open up a dialog wherein we can select the fields to generate Getters and Setters.