In the last lesson anyone could write ben.score = -500;. Nothing stops nonsense getting in. Encapsulation means a class keeps its fields to itself and offers methods to use them, so it can check every change and keep its own rules true.
Mark fields private and only code inside the class can touch them. Then add public methods for what others may do. A method that reads a field is a getter; one that changes it with a check is often a setter or a method named for the action.
Java
public class Main {
static class BankAccount {
private final String owner;
private int balance;
BankAccount(String owner) {
this.owner = owner;
}
public int getBalance() { return balance; }
public String getOwner() { return owner; }
public void deposit(int amount) {
if (amount <= 0) {
System.out.println("Deposit must be positive");
return;
}
balance += amount;
}
public boolean withdraw(int amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
}
public static void main(String[] args) {
BankAccount acc = new BankAccount("Ana");
acc.deposit(100);
acc.deposit(-5);
System.out.println(acc.withdraw(30));
System.out.println(acc.withdraw(500));
System.out.println(acc.getOwner() + ": " + acc.getBalance());
}
}
Prints
Deposit must be positive
true
false
Ana: 70
Now the balance can only change through deposit and withdraw, and both check their input. Outside code writing acc.balance = 1000000; won't compile. The owner is final: set once in the constructor and never again, so there's no setter for it.
Access levels
private: only inside this class. The default choice for fields.
no word (package access): classes in the same package (folder).
protected: the package, plus subclasses (next lesson).
public: anyone.
A good habit: fields private, and only the methods others really need public. The fewer ways in, the fewer ways to break it, and the freer you are to change the inside later without breaking other code.
static: belonging to the class
Normal fields belong to each object. A static field belongs to the class itself: there's one copy, shared by every object. A static method doesn't run on an object at all, so it can't use the normal fields; you call it on the class name, like Math.max(...). That's also why main is static: it runs before any object exists.
Java
public class Main {
static class Ticket {
private static int issued = 0;
private final int number;
Ticket() {
issued++;
number = issued;
}
int getNumber() { return number; }
static int howMany() { return issued; }
}
public static void main(String[] args) {
Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
System.out.println(b.getNumber());
System.out.println(Ticket.howMany());
}
}
Prints
2
3
A constant shared by everything is usually static final, in capitals: static final int MAX_SEATS = 40;.
More than one constructor
A class can have several constructors with different parameters (this is called overloading, and methods can do it too). One constructor can call another with this(...) to avoid repeating itself:
Java
public class Main {
static class Pizza {
private final String size;
private final int toppings;
Pizza(String size, int toppings) {
this.size = size;
this.toppings = toppings;
}
Pizza(String size) {
this(size, 0);
}
int price() {
int base = size.equals("large") ? 12 : 8;
return base + toppings * 2;
}
}
public static void main(String[] args) {
System.out.println(new Pizza("large", 3).price());
System.out.println(new Pizza("small").price());
}
}
Prints
18
8
size.equals("large") ? 12 : 8 is the ternary operator: if the condition is true, the first value, otherwise the second. It's a compact if that gives back a value.
Don't add a setter for every field by reflex. Ask what a caller actually needs to do (deposit, rename, cancel) and offer that, with its checks.
Practice
Why make a field private?
More info
Quick reference
private
Visible only inside the class.
public
Visible everywhere.
getter
A method that hands out a field's value: getBalance().