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; }}
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; }}
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.