Skip to lesson

Getters and setters

A getter is a public method that returns the value of a private field. A setter is a public method that takes a new value and saves it in the field. Together they are the controlled way to read and change an object’s data.

What getters and setters are

A getter (accessor) is a public method that returns the value of a private field, like getName(). A setter (mutator) is a public method that takes a new value, checks it if needed, and stores it in a private field, like setName(String name).

With a private name, main can no longer write s.name. So the class offers a getter, getName(), to read it, and a setter, setName(String name), to change it.

Example 1 · A getter and a setter for one field

GetSetDemo.javaJava
class Student {    private String name;
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }}
public class GetSetDemo {    public static void main(String[] args) {        Student s = new Student();        s.setName("Kavya");        System.out.println("Name: " + s.getName());        s.setName("Kavya Rao");        System.out.println("Name: " + s.getName());    }}
Output
Name: Kavya
Name: Kavya Rao

What this code does

  • setName saves the value in the private field; getName returns it. main never touches the field itself.
  • this.name is the field and name is the parameter, so the value lands in the object.

You may also hear the formal names: an accessor is a method that reads (a getter), and a mutator is a method that changes (a setter).

How to name them

A naming convention is a naming habit that all Java programmers and tools follow, though the compiler does not check it. For getters and setters: getX(), isX() for a boolean, and setX(value).

Java programmers follow a naming convention: a habit everyone uses, not a compiler rule. A getter is get plus the field name with a capital letter, and a boolean getter starts with is.

Example 2 · Naming rules in one class, with isX for a boolean

ProductDemo.javaJava
class Product {    private String name;    private int price;    private boolean inStock;
    public Product(String name, int price) {        this.name = name;        this.price = price;    }
    public String getName() { return name; }    public int getPrice() { return price; }    public boolean isInStock() { return inStock; }
    public void setPrice(int price) { this.price = price; }    public void setInStock(boolean inStock) { this.inStock = inStock; }}
public class ProductDemo {    public static void main(String[] args) {        Product p = new Product("Earbuds", 1999);        p.setInStock(true);        p.setPrice(1799);        if (p.isInStock()) {            System.out.println(p.getName() + " in stock at Rs. " + p.getPrice());        }    }}
Output
Earbuds in stock at Rs. 1799

What this code does

  • The boolean field inStock has the getter isInStock(), which reads well in an if. Its setter is still setInStock.
  • name has no setter: the product’s name is fixed once it is created.

The full rules, which IDEs and many Java tools expect:

  • Getter: get + name. name → getName(). No parameters; returns the field's type.
  • Getter for a boolean: is + name. paid → isPaid(), inStock → isInStock().
  • Setter: set + name. price → setPrice(int price). Returns void; takes one value of the field's type.
  • Setter for a boolean: still set. paid → setPaid(boolean paid).

this in setters

A passenger's city is set to Chennai, yet the getter prints null. Inside setCity(String city), plain city means the parameter, so city = city; copies the parameter into itself.

Example 3 · The setter that sets nothing

SetterBugDemo.javaJava
class Passenger {    private String city;
    public void setCity(String city) {        city = city;    }
    public String getCity() {        return city;    }}
public class SetterBugDemo {    public static void main(String[] args) {        Passenger p = new Passenger();        p.setCity("Chennai");        System.out.println("City: " + p.getCity());    }}
Output
City: null

What this code does

  • The parameter city hides the field, so city = city; copies the parameter into itself.
  • The field keeps its default value null. The trace below shows the two city variables side by side.

Write this.city = city; to reach the field, as in The this keyword (opens in a new tab). A getter has no parameter hiding the field, so return city; needs no this.

Trace the code

Watch the setter miss the field

class Passenger {
private String city;
public void setCity(String city) {
city = city;
}
public String getCity() {
return city;
}
}
public class SetterTrace {
public static void main(String[] args) {
Passenger p = new Passenger();
p.setCity("Chennai");
System.out.println("City: " + p.getCity());
}
}

Variables

p
city = null

Output

(nothing printed yet)

Line 15new builds the Passenger. Its private field city starts as null.

Step 1 of 5

When not to add a setter

Arjun's roll number must never change after admission. Then give it no setter at all: set it in the constructor, add a getter, and any setRollNo call fails to compile.

Example 4 · No setter means no change

NoSetterDemo.javaJava
class Student {    private int rollNo;    private String name;
    public Student(int rollNo, String name) {        this.rollNo = rollNo;        this.name = name;    }
    public int getRollNo() {        return rollNo;    }}
public class NoSetterDemo {    public static void main(String[] args) {        Student s = new Student(21, "Arjun");        s.setRollNo(5);    }}
Sample compiler output
NoSetterDemo.java:18: error: cannot find symbol
        s.setRollNo(5);
         ^
  symbol:   method setRollNo(int)
  location: variable s of type Student
1 error

What this code does

  • The roll number is set once in the constructor. There is no setRollNo, so javac cannot find it.
  • cannot find symbol means "no method or variable with this name exists here". Here, that is exactly what we want.

Example 5 · A setter with no check lets wrong values in

OpenSetterDemo.javaJava
class Product {    private int price;
    public void setPrice(int price) {        this.price = price;    }
    public int getPrice() {        return price;    }}
public class OpenSetterDemo {    public static void main(String[] args) {        Product p = new Product();        p.setPrice(-500);        System.out.println("Price: Rs. " + p.getPrice());    }}
Output
Price: Rs. -500

What this code does

  • The field is private, but the setter accepts any int, so a negative price still gets in.
  • A setter is only as safe as its check. The next lesson adds checks to setters and constructors.

A setter with no check is almost the same as a public field: any value goes in (Example 5). So do not add a getter and a setter for every field by habit. For each field, ask whether outside code should change it, and how:

  • Fixed after creation (roll number, account number, PNR) → set it in the constructor; getter only.
  • Changes only through actions (a bank balance) → methods like deposit, not setBalance.
  • Private details (a PIN) → often no getter either.
  • Free to change, with a rule (marks, price) → a setter that checks the value, as in Keep objects valid with checks (opens in a new tab).
Most IDEs can generate getters and setters in one click. Decide first which ones the class really needs, then generate only those.

Spot the getter and setter bug

Each snippet is meant to read or change one field. Read the real javac error, then pick the line that fixes it.

Fix the error

Fix the getter or setter error

Read the error, then pick the line that fixes it.

Round 1 of 4

getPrice() should hand the price back to the caller.

class Product {
private int price;
public int getPrice() {
System.out.println(price);
}
}

Error

Product.java:5: error: missing return statement

Next step

Check your understanding

12 quick questions