When to use get/set Methods in java

Jovan picture Jovan · Nov 11, 2010 · Viewed 79.9k times · Source

I want to know when to use get and set methods(getName,setName ) in my class and when simple classVariable.name = "" instead а = classVariable.getName()

Here is example of class using set and get methods

public class ClassExampe {

    String name;
    String course;

    public String getName ( )
    {
        return name;
    }

    public void setName (String studentName)
    {
        name = studentName;           
    }

    public String getCourse ( )
    {
        return course;
    }

    public void setCourse (String studentCourse)
    {
        course = studentCourse;
    }
}

Thanks

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Nov 11, 2010

Using Getters / Setters vs using Fields

As a rule of thumb:

use the variables directly from the same class (actually from the same .java file, so inner classes are ok too), use Getters / Setters from other classes.