AI Hints
Home›Java Tutorial›Access Modifiers, Getters and Setters, and toString
Java · Lesson 71 of 120

Getters and Setters

Controlled access.

⏱ 2 min read▶ Video at 1:29:23🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

If fields are private, how do other classes read them? With small public methods, called getters, and setters.

  • Fields are private
  • Getters read
  • Setters change

Getters and setters

Get owner returns the owner, so others can read it. Get balance does the same. There's no set balance, so nobody can just set it. Set owner changes the owner, but first checks the new value. An empty name is refused.

Main.javajava
public class Account {
    private String owner;
    private double balance;
    public Account(String owner) { this.owner = owner; }

    public String getOwner() { return owner; }
    public double getBalance() { return balance; }

    public void setOwner(String owner) {
        if (owner == null || owner.isBlank()) {
            System.out.println("Owner can't be empty");
            return;
        }
        this.owner = owner;
    }
    public void deposit(double amount) { if (amount > 0) balance += amount; }
}

Using them

We deposit fifty, then try minus twenty, which is ignored. Then we try to set an empty owner, which is refused. Run it. Lena has fifty. The empty name is rejected. And the owner becomes Lena Park.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Account acc = new Account("Lena");
        acc.deposit(50);
        acc.deposit(-20);
        System.out.println(acc.getOwner() + " has " + acc.getBalance());
        acc.setOwner("");
        acc.setOwner("Lena Park");
        System.out.println("Owner is now " + acc.getOwner());
    }
}
Output
Lena has 50.0
Owner can't be empty
Owner is now Lena Park
Also uses Account.java
public class Account {
    private String owner;
    private double balance;
    public Account(String owner) { this.owner = owner; }

    public String getOwner() { return owner; }
    public double getBalance() { return balance; }

    public void setOwner(String owner) {
        if (owner == null || owner.isBlank()) {
            System.out.println("Owner can't be empty");
            return;
        }
        this.owner = owner;
    }
    public void deposit(double amount) { if (amount > 0) balance += amount; }
}

Why bother

Getters and setters let a class check every change. You can make a field read only, by having no setter. You can change how data is stored later, without breaking other code. This is the heart of encapsulation.

keyvalue
Checkevery change
Read onlygetter, no setter
Change freelyinside the class
Nameencapsulation

Summary

Getters read private fields, and setters change them, with checks. Leave out a setter, to make a field read only. Next, how objects print themselves.

Key takeaways
  • getX()
  • setX(value)
  • Validate in setters
Next up: toString — how an object prints