Activity Forums Salesforce® Discussions What are getter methods and setter methods?

  • shariq

    Member
    September 22, 2018 at 11:02 am

    Get (getter) method is used to pass values from the controller to the VF page.
    Whereas, the set (setter) method is used to set the value back to controller variable.

    I hope this set of Salesforce interview questions will help you ace your job interview. As the next step for your career, check out the various certifications offered by Salesforce here: Salesforce Certifications. It will also help you to understand the job roles and chalk out a career path for yourself.

    Also, check out this video on the Top 50 Frequently Asked Salesforce Interview Questions which was delivered by an industry expert. He has shared his opinion of Salesforce job interviews and industry demand. Do take a at it look and let us know if this helped in your interview preparation.

  • Parul

    Member
    September 22, 2018 at 12:48 pm

    Hi

    Getter and Setter methods are used when you want to get or set a field (int, String, etc) which is private in a class, from outside the class. Not all variables can be made public and static for obvious reasons.

    Suppose you have a class User :

    Class User {

    private String username;

    private String password;

    }

    For every new user, you will need a new instance of class User.

    User new_user = new User();

    Suppose you want to set the password for instance new_user. Since password is a private variable, you can't access it from outside.

    Instead, you create a public method which can help you access the variable.

    Class User {

    private String username;

    private String password;

    public String getPassword() {

    return password;

    }

    public void setPassword (String p){

    password = p;

    }

    }

    Now you can get/ set password through these methods.

    new_user.setPassword(“29091992”); will set the password to 29091992.

    Similarly new_user.getPassword(); will fetch the password for this instance.

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos