1

How and why getter adn setter methods are used in apex? For Ex: What does this line of code does? Public String companyname{get;set;} And where in your code these methods be ideally used?

0

2 Answers 2

1

There's already a question with an answer here which offers a really good explanation into getters and setters, where and how they should be used. There's also an explantion right here on Stack Exchange!

Have a read of those, they'll definately bring you up to speed on what it is they do!

Hope this'll help!

1
  • In other words it's a duplicate! Generally you should vote to close in that case, even if this answer is helpful.
    – Adrian Larson
    Commented Jul 29, 2015 at 13:45
1

Setter : set data from VF page component to class variable .
Getter : get data from class variable to VF page Component.
Action : Apex Class Methods which perform some operation

Execution Flow

When Page Loaded or refresh : Constructor --> Getter

When action is called(For ex Command button) : Setter --> Action --> Getter

when you specify a data Member in apex class like Public String companyname{get;set;} internally how getter and setter invoked you can check by this example.... here i define getter and setter manually for num1, num2..
Here is a simple example that would be helpful for you....

enter image description here

    <apex:pageBlockSection >
          <apex:pageBlockSectionItem >
                 <apex:outputText value="Enter First Value"/>
                 <apex:inputText value="{!num1}"/>
         </apex:pageBlockSectionItem>                  <br/>
         <apex:pageBlockSectionItem >
                <apex:outputText value="Enter Second Value"/>
                 <apex:inputText value="{!num2}"/>
        </apex:pageBlockSectionItem>                   <br/>

        <apex:pageBlockSectionItem >
                <apex:commandButton value="Add" action="{!addition}"/>          
      </apex:pageBlockSectionItem>               <br/>

          <apex:pageBlockSectionItem >
                <apex:outputText value="The Result ="/>
                 <apex:outputText value="{!res}" />
        </apex:pageBlockSectionItem>

     </apex:pageBlockSection>


Class

public class Addclass {

      integer num1;
      integer num2;
      integer res;

    public AddClass () {
       num1=num2=res=0; 
    }  
    public integer getnum1() {
       return num1;
    }          
    public integer getnum2() {
       return num2;
    }
    public integer getres() {
       return res;
    }
    public void setNum1(Integer n1){
       num1 = n1;
    }
    public void setNum2(Integer n2){
       num2 = n2;
    }
    public void addition(){

        res=num1+num2;          
    }   
}

Not the answer you're looking for? Browse other questions tagged .