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

  • 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.