Java Tutorial
Java Encapsulation
Encapsulation keeps fields private and exposes controlled getters and setters so the class can protect its own rules — no negative balances, no empty names.
Hide the data, publish the API
Encapsulation means the object owns its state. Callers ask through methods; they do not poke fields. That way you can change how values are stored later without rewriting every line that used the class.
Example
class Account {
private double balance;
public Account(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account(100);
a.deposit(40);
System.out.println(a.getBalance()); // 140
}
}Setters enforce rules
A setter is not just this.x = x. It is a gate: reject bad values, clamp ranges, or update related fields. Without encapsulation, every caller would have to remember those rules on their own.
Example
class Player {
private String name;
private int score;
public void setName(String name) {
if (name != null && !name.isBlank()) {
this.name = name;
}
}
public void setScore(int score) {
if (score >= 0) this.score = score;
}
public String getName() { return name; }
public int getScore() { return score; }
}
public class Main {
public static void main(String[] args) {
Player p = new Player();
p.setName("Rin");
p.setScore(10);
p.setScore(-5); // ignored
System.out.println(p.getName() + " " + p.getScore()); // Rin 10
}
}Not every field needs a setter
Some values should be read-only after construction: an ID, a creation time, a name that never changes. Provide a getter (or none) and set the field only in the constructor.
Example
class User {
private final String id;
private String displayName;
public User(String id, String displayName) {
this.id = id;
this.displayName = displayName;
}
public String getId() { return id; }
public String getDisplayName() { return displayName; }
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
public class Main {
public static void main(String[] args) {
User u = new User("u42", "Ada");
u.setDisplayName("Ada Lovelace");
System.out.println(u.getId() + " " + u.getDisplayName());
}
}Encapsulation is not bureaucracy. It is how you keep invariants true — "balance never goes negative" lives in one method instead of in twenty call sites.
Try It Yourself
Exercise: Encapsulate a Temperature class with a private double celsius. Add setCelsius that rejects values below -273.15, plus getCelsius. Demonstrate a rejected update in main.
Show solution
class Temperature {
private double celsius;
public void setCelsius(double celsius) {
if (celsius >= -273.15) this.celsius = celsius;
}
public double getCelsius() {
return celsius;
}
}
public class Main {
public static void main(String[] args) {
Temperature t = new Temperature();
t.setCelsius(20);
t.setCelsius(-300); // ignored
System.out.println(t.getCelsius()); // 20.0
}
}The setter owns the absolute-zero rule; callers cannot bypass it by writing the field.
Key Takeaways
- Keep fields private; expose behavior through public methods.
- Getters read state; setters can validate before changing it.
- Not every field needs a setter — some values are constructor-only.
- Invariants live in one place instead of being scattered across callers.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Statistics
Guard a score
private hides the field. set rejects negatives so averages never see an impossible mark.
Example
class Score {
private int n;
void set(int v) { if (v >= 0) n = v; }
int get() { return n; }
}
public class Main {
public static void main(String[] args) {
Score s = new Score();
s.set(-3);
s.set(88);
System.out.println(s.get());
}
}