6.1 Classes, Objects, and Encapsulation
Object-oriented programming, or OOP, models things as objects. An object stores data and provides behavior. A class is a template, and an object is an instance of that class.
Classes and Objects
The BankAccount class below represents a bank account. owner, account, and balance are fields. deposit() and withdraw() are methods.
class BankAccount {
String owner;
String account;
double balance;
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
balance -= amount;
}
}
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.owner = "Alice";
account.account = "6250941006528599";
account.balance = 50;
account.deposit(100);
System.out.println("Balance: " + account.balance);
}
}Output:
Balance: 150.0When account.deposit(100) runs, the method works on the current account object. If a method needs to refer to the current object explicitly, Java uses this.
Encapsulation
Encapsulation hides internal implementation details and lets outside code access or change state through clear methods.
If account balance can be changed freely from outside, it is hard to keep data valid. A better design makes balance private and checks changes through methods.
class BankAccount {
private String owner;
private String account;
private double balance;
BankAccount(String owner, String account, double balance) {
this.owner = owner;
this.account = account;
this.balance = balance;
}
double getBalance() {
return balance;
}
boolean deposit(double amount) {
if (amount <= 0) {
return false;
}
balance += amount;
return true;
}
boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return false;
}
balance -= amount;
return true;
}
}Private fields are not meant to make code mysterious. They keep state changes inside trusted methods.
Constructor
A constructor runs automatically when an object is created with new.
BankAccount account = new BankAccount("Alice", "6250941006528599", 50);Constructors are commonly used to set initial object state. If an object should always have certain fields, initialize them in the constructor.