Understand how classes define structure and objects hold state.
Published January 15, 2025
In Java, a class is a blueprint that describes the structure and behaviour of objects. An object is an instance of a class — it holds concrete data.
public class BankAccount {
private String owner;
private double balance;
public BankAccount(String owner, double initialBalance) {
this.owner = owner;
this.balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
}
BankAccount account = new BankAccount("Alice", 1000.0);
account.deposit(500.0);
System.out.println(account.getBalance()); // 1500.0
private and exposes behaviour through public methodsthis keywordthis refers to the current object. Use it to disambiguate between a field and a parameter with the same name.
public void setOwner(String owner) {
this.owner = owner; // this.owner = field, owner = parameter
}
When asked about OOP, explain all four pillars: Encapsulation, Inheritance, Polymorphism, Abstraction. Use BankAccount as your go-to example — it naturally demonstrates encapsulation.