Object-Oriented Programming in Java
Classes and objects
public class Account {
private final String owner;
private double balance;
public Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amount;
}
public double getBalance() { return balance; }
@Override
public String toString() { return owner + ": " + balance; }
}
The four pillars
| Pillar | Idea | Java feature |
|---|---|---|
| Encapsulation | Hide state behind methods | private fields, getters and setters |
| Inheritance | Reuse and specialise | extends |
| Polymorphism | One interface, many behaviours | Overriding, interfaces |
| Abstraction | Expose what, hide how | abstract classes, interfaces |
Inheritance and polymorphism
abstract class Shape {
abstract double area();
}
class Rectangle extends Shape {
private final double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
Shape[] shapes = { new Rectangle(2, 3), new Circle(1) };
for (Shape s : shapes) System.out.println(s.area()); // dynamic dispatch
Interfaces
interface Payable {
double amountDue();
default String label() { return "Payable"; } // default method
}
A class can implement many interfaces but extend only one class.
Useful concepts
| Concept | Notes |
|---|---|
| Overloading vs overriding | Same name, different parameters / same signature in a subclass |
static | Belongs to the class, not an instance |
final | Cannot be reassigned, overridden or extended |
| Access modifiers | private, package-private, protected, public |
equals and hashCode | Override together for use in hash-based collections |
| Records (Java 16+) | record Point(int x, int y) {} for immutable data classes |
Loading Comments...