Phase 12: The 4 Pillars Implemented in Code
See all 4 OOP Pillars side-by-side in executable Java code snippet form.
Pillar 1: Encapsulation in Code
public class BankAccount {
private double balance; // Private field protects state
public BankAccount(double initialBalance) {
if (initialBalance >= 0) this.balance = initialBalance;
}
public double getBalance() { return this.balance; }
public void deposit(double amount) {
if (amount > 0) this.balance += amount; // Protected invariant
}
}
Pillar 2: Abstraction in Code
// Interface defines abstract contract (what to do, hiding how)
public interface PaymentGateway {
boolean processPayment(double amount);
}
// Concrete class implements internal payment details
public class StripePayment implements PaymentGateway {
@Override
public boolean processPayment(double amount) {
// Complex HTTP API call abstracted away!
System.out.println("Processing $" + amount + " via Stripe.");
return true;
}
}
Pillar 3: Inheritance in Code
// Superclass (Parent)
public class Employee {
protected String name;
protected double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
}
// Subclass (Child) inherits name and salary from Employee (IS-A relationship)
public class SoftwareEngineer extends Employee {
private String programmingLanguage;
public SoftwareEngineer(String name, double salary, String lang) {
super(name, salary); // Reuses parent constructor!
this.programmingLanguage = lang;
}
}
Pillar 4: Polymorphism in Code
public class Main {
public static void main(String[] args) {
// Polymorphic reference array (Parent reference -> Child objects)
PaymentGateway[] gateways = new PaymentGateway[] {
new StripePayment(),
new PayPalPayment()
};
// Same interface method call produces multiple different behaviors!
for (PaymentGateway pg : gateways) {
pg.processPayment(150.0);
}
}
}