Apex Getter and Setter methods
When we want to refer Apex class variables in the visualforce page we need to use Apex getter and setter methods. In this Salesforce tutorial, we will understand about Apex getter method and setter method in detail.
- Setter method : This will take the value from the visualforce page and stores to the Apex variable name.
- getter method : This method will return a value to a visualforce page whenever a name variable is called.
public class Example {
public void Set(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
get method ( )
When visualforce page want to get the value of a variable defined in the Apex. It will invoke get method of that variable.
Example
<apex:outputlabel > {!name} </apex:outputlabel>
In the above example, Visualforce page is trying to use name variable which is declared in Apex class. So it invokes automatically getname( ) method in the Apex class and this method will return the value of that variable.
Example for getter method using visualforce and Apex class is as shown in the following code snippet.
public class Prasanth {
String name;
public String getName() {
return 'Tutoriart.com';
}
}
Visualforce page
<apex:page controller="example2" sidebar="false">
<apex:outputLabel> {!name}</apex:outputLabel>
</apex:page>
As shown above, when the page is loaded first it creates an object for prasanth class. When outputlabel calls {!name} in the Visualforce page, it invokes getname( ) method in the controller class.
Output
Setter method
Setter method will take the value from the visualforce page and stores to the Apex variable name.To understand about setter method ( ), let us write an Apex class for passing the values and saving the values to Apex variables.
An Apex class to demonstrate Setter method
public class setter {
public string name;
public string getname() {
return name;
}
public void Setname(String name) {
this.name=name;
}
}
Visualforce page
<apex:page controller="setter">
<apex:form>
<apex:outputLabel> Enter name </apex:outputLabel>
<apex:inputText value="{!name}"/>
<apex:commandButton value="click" reRender="one"/>
<div>
<apex:outputLabel id="one"> Hello your name is {!name}
</apex:outputLabel>
</div>
</apex:form>
</apex:page>
In the above example, we have written simple Apex code to pass the values and save the values to Apex variables.