What are Getter and setter methods ?
Getter method is to retrieve the value of instance variable while a setter method is used to set or update the value of instance variable. It is a good practice to access instance variables through these methods instead of directly accessing because we can place some pre-conditions before setting or getting the value of these variables.
Example :- If we have an instance variable as amount and we want that always the ‘amount’ value should be greater than 1000. So we can create a setter method which will only assign value to ‘amount’ if greater than 1000.
class Bank {
private int amount;
//setter method checking if the amount is greater than 1000
public String setAmount(int temp){
if(temp>1000){
amount=temp;
}else{
return "Enter amount greater than 1000";
}
return "Saved successfully";
}
//getter method
public int getAmount(){
return amount;
}
}
If we have ten instance variables in a program then it will be time taking to create getter and setter method for each variable manually. So Eclipse IDE provides a short way to create getter and setter methods on a single click.
Let us see shortcut to create Getter and Setters in Eclipse :
Step 1 : Declare all the variables in the program.
Step 2 : Right click anywhere in the code and select ‘Source‘ and then select ‘Generate Getters and Setters…‘.
Step 3 : Now a dialog box will open. In the dialog box select the variables of which you want to generate Getter and Setter. After selecting variables click on ‘Generate‘ button.
Step 4 : Getter and Setter methods will be created for the selected variables.
Let us now understand an important topic – How to debug code in Eclipse