3 Hours

2. Object-Oriented Programming & SOLID Principles

Core Java
Sandbox Note: The editor validates your Java syntax and compilation only. It does NOT run a Spring Boot server. When you see Compilation successful (exit code 0), your code is syntactically correct. Copy it to your local IDE and run with ./mvnw spring-boot:run to test.

Spring Boot is built on Object-Oriented Programming (OOP). Every Spring application is composed of objects (beans) that collaborate to handle requests, manage data, and enforce business rules. Understanding OOP and SOLID principles is not optional — it is the foundation of writing maintainable Spring applications.

The Four Pillars of OOP

Before we write a single line of Spring code, you must be comfortable with these four concepts. Spring uses them everywhere.

1. Encapsulation (Bundling Data with Methods)

Encapsulation hides internal state and requires all interaction to happen through methods. In Spring, your service classes encapsulate business logic, and your repositories encapsulate database access.

Java
public class BankAccount {
    private double balance;  // Private state - cannot be accessed directly

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}
// Spring equivalent: @Service encapsulates business logic, @Repository encapsulates data access
To test this code: Compile with javac BankAccount.java. The sandbox validates syntax; run locally to test deposit logic.

2. Inheritance (Reusing Parent Behavior)

Inheritance allows a class to inherit fields and methods from a parent class. Spring uses inheritance extensively — your repository interfaces extend JpaRepository, and your configuration classes extend WebSecurityConfigurerAdapter (or use security filters).

Java
public class Vehicle {
    protected String brand;
    public void honk() { System.out.println("Beep!"); }
}

public class Car extends Vehicle {
    private int doors;
    @Override
    public void honk() { System.out.println("Car horn!"); }
}
// Spring: public interface UserRepository extends JpaRepository<User, Long>

3. Polymorphism (Many Forms)

Polymorphism allows objects of different types to be treated as objects of a common parent type. Spring's dependency injection relies on this — you code to interfaces, and Spring injects the concrete implementation.

Java
public interface PaymentService {
    void processPayment(double amount);
}

public class CreditCardPayment implements PaymentService {
    public void processPayment(double amount) {
        System.out.println("Processing credit card: $" + amount);
    }
}

public class PayPalPayment implements PaymentService {
    public void processPayment(double amount) {
        System.out.println("Processing PayPal: $" + amount);
    }
}

// Spring injects the correct implementation based on configuration
@Service
public class CheckoutService {
    private final PaymentService paymentService;  // Polymorphic reference
    // Spring decides which PaymentService to inject
}

4. Abstraction (Hiding Implementation Details)

Abstraction hides complex implementation details and exposes only what is necessary. Spring repositories are perfect examples — you write an interface, and Spring Data JPA provides the implementation automatically.

Java
// You write only the interface
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

// Spring automatically provides the implementation
// You never see the complex SQL generation, connection management, or transaction handling

The SOLID Principles

SOLID is a set of five design principles that make software more maintainable. Spring Boot was designed with these principles in mind, and following them will make your Spring code clean and testable.

S: Single Responsibility Principle

A class should have only one reason to change. In Spring, this means separate classes for separate concerns.

Java
// BAD: One class doing too much
public class UserService {
    public void createUser() { /* user creation */ }
    public void sendEmail() { /* email sending */ }
    public void logActivity() { /* logging */ }
}

// GOOD: Separate responsibilities
@Service
public class UserService {
    private final EmailService emailService;
    private final AuditService auditService;
    // Each class has ONE job
}

O: Open/Closed Principle

Classes should be open for extension but closed for modification. Spring's interface-based design enables this.

Java
// Define an interface
public interface DiscountStrategy {
    double applyDiscount(double price);
}

// Add new strategies without changing existing code
@Component
public class SummerDiscount implements DiscountStrategy { }
@Component
public class HolidayDiscount implements DiscountStrategy { }

// The service works with any DiscountStrategy
@Service
public class PriceService {
    private final DiscountStrategy discount;
    // Can inject ANY DiscountStrategy without changing PriceService
}

L: Liskov Substitution Principle

Subtypes must be substitutable for their base types. This is why Spring's proxy mechanism works — you can swap implementations freely.

Java
// Any implementation of UserRepository can be swapped in
public interface UserRepository {
    User findById(Long id);
}

// All these are substitutable
public class JpaUserRepository implements UserRepository { }
public class MongoUserRepository implements UserRepository { }
public class MockUserRepository implements UserRepository { }

I: Interface Segregation Principle

Clients should not be forced to depend on interfaces they do not use. Spring Data JPA follows this with specialized interfaces.

Java
// Instead of one giant interface
public interface CrudRepository<T, ID> { /* basic CRUD */ }
public interface PagingAndSortingRepository<T, ID> extends CrudRepository { /* pagination */ }
public interface JpaRepository<T, ID> extends PagingAndSortingRepository { /* JPA specific */ }

// Your repository only extends what it needs
public interface UserRepository extends JpaRepository<User, Long> { }

D: Dependency Inversion Principle

Depend on abstractions, not concretions. This is the core of Spring's Dependency Injection.

Java
// BAD: Depends on concrete class
@Service
public class OrderService {
    private PostgresUserRepository userRepository;  // Concrete
}

// GOOD: Depends on abstraction
@Service
public class OrderService {
    private final UserRepository userRepository;  // Interface
}
// Spring injects the concrete implementation automatically
Local Testing: Compile with javac *.java. The sandbox validates your syntax; run locally to see the output.

Knowledge Check

Ready to test your understanding of 2. Object-Oriented Programming & SOLID Principles?

Back