|
| 1 | +# Module 1: Object-Oriented Programming |
| 2 | + |
| 3 | +## 📋 Overview |
| 4 | +Essential OOP concepts that form the foundation of Spring Framework development. |
| 5 | + |
| 6 | +## 🎯 Learning Objectives |
| 7 | +- Master the four pillars of OOP |
| 8 | +- Understand Java class design principles |
| 9 | +- Apply SOLID principles effectively |
| 10 | +- Recognize OOP patterns used in Spring |
| 11 | + |
| 12 | +## 📚 Core Concepts |
| 13 | + |
| 14 | +### 1. Encapsulation |
| 15 | +**Definition**: Bundling data and methods that operate on that data within a single unit. |
| 16 | + |
| 17 | +```java |
| 18 | +public class BankAccount { |
| 19 | + private double balance; // Encapsulated field |
| 20 | + private String accountNumber; |
| 21 | + |
| 22 | + // Controlled access through methods |
| 23 | + public double getBalance() { |
| 24 | + return balance; |
| 25 | + } |
| 26 | + |
| 27 | + public void deposit(double amount) { |
| 28 | + if (amount > 0) { |
| 29 | + balance += amount; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public boolean withdraw(double amount) { |
| 34 | + if (amount > 0 && amount <= balance) { |
| 35 | + balance -= amount; |
| 36 | + return true; |
| 37 | + } |
| 38 | + return false; |
| 39 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +**Spring Relevance**: Spring beans use encapsulation to hide internal state and expose controlled interfaces. |
| 44 | + |
| 45 | +### 2. Inheritance |
| 46 | +**Definition**: Mechanism where a new class inherits properties and methods from an existing class. |
| 47 | + |
| 48 | +```java |
| 49 | +// Base class |
| 50 | +public abstract class Vehicle { |
| 51 | + protected String brand; |
| 52 | + protected int year; |
| 53 | + |
| 54 | + public Vehicle(String brand, int year) { |
| 55 | + this.brand = brand; |
| 56 | + this.year = year; |
| 57 | + } |
| 58 | + |
| 59 | + // Template method pattern |
| 60 | + public abstract void start(); |
| 61 | + |
| 62 | + public void displayInfo() { |
| 63 | + System.out.println(brand + " " + year); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +// Derived class |
| 68 | +public class Car extends Vehicle { |
| 69 | + private int doors; |
| 70 | + |
| 71 | + public Car(String brand, int year, int doors) { |
| 72 | + super(brand, year); |
| 73 | + this.doors = doors; |
| 74 | + } |
| 75 | + |
| 76 | + @Override |
| 77 | + public void start() { |
| 78 | + System.out.println("Car engine started"); |
| 79 | + } |
| 80 | +} |
| 81 | +``` |
| 82 | + |
| 83 | +**Spring Relevance**: Spring uses inheritance in many places, like extending `ApplicationContextAware` or implementing callback interfaces. |
| 84 | + |
| 85 | +### 3. Polymorphism |
| 86 | +**Definition**: Ability of objects of different types to be treated as instances of the same type through a common interface. |
| 87 | + |
| 88 | +```java |
| 89 | +// Interface defining contract |
| 90 | +public interface PaymentProcessor { |
| 91 | + boolean processPayment(double amount); |
| 92 | + String getPaymentMethod(); |
| 93 | +} |
| 94 | + |
| 95 | +// Different implementations |
| 96 | +public class CreditCardProcessor implements PaymentProcessor { |
| 97 | + @Override |
| 98 | + public boolean processPayment(double amount) { |
| 99 | + // Credit card processing logic |
| 100 | + return true; |
| 101 | + } |
| 102 | + |
| 103 | + @Override |
| 104 | + public String getPaymentMethod() { |
| 105 | + return "Credit Card"; |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +public class PayPalProcessor implements PaymentProcessor { |
| 110 | + @Override |
| 111 | + public boolean processPayment(double amount) { |
| 112 | + // PayPal processing logic |
| 113 | + return true; |
| 114 | + } |
| 115 | + |
| 116 | + @Override |
| 117 | + public String getPaymentMethod() { |
| 118 | + return "PayPal"; |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +// Polymorphic usage |
| 123 | +public class PaymentService { |
| 124 | + public void processOrder(PaymentProcessor processor, double amount) { |
| 125 | + if (processor.processPayment(amount)) { |
| 126 | + System.out.println("Payment successful via " + processor.getPaymentMethod()); |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | +``` |
| 131 | + |
| 132 | +**Spring Relevance**: Dependency injection relies heavily on polymorphism to inject different implementations. |
| 133 | + |
| 134 | +### 4. Abstraction |
| 135 | +**Definition**: Hiding complex implementation details while exposing only essential features. |
| 136 | + |
| 137 | +```java |
| 138 | +// Abstract class providing template |
| 139 | +public abstract class DatabaseConnection { |
| 140 | + // Template method |
| 141 | + public final void connect() { |
| 142 | + openConnection(); |
| 143 | + authenticate(); |
| 144 | + configureSettings(); |
| 145 | + } |
| 146 | + |
| 147 | + // Abstract methods to be implemented by subclasses |
| 148 | + protected abstract void openConnection(); |
| 149 | + protected abstract void authenticate(); |
| 150 | + |
| 151 | + // Common implementation |
| 152 | + protected void configureSettings() { |
| 153 | + System.out.println("Applying default settings"); |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +// Interface for data access abstraction |
| 158 | +public interface UserRepository { |
| 159 | + User findById(Long id); |
| 160 | + List<User> findAll(); |
| 161 | + void save(User user); |
| 162 | + void delete(Long id); |
| 163 | +} |
| 164 | +``` |
| 165 | + |
| 166 | +**Spring Relevance**: Spring Data repositories are perfect examples of abstraction in action. |
| 167 | + |
| 168 | +## 🏗️ SOLID Principles |
| 169 | + |
| 170 | +### Single Responsibility Principle (SRP) |
| 171 | +Each class should have only one reason to change. |
| 172 | + |
| 173 | +```java |
| 174 | +// BAD: Multiple responsibilities |
| 175 | +public class UserProcessor { |
| 176 | + public void saveUser(User user) { /* DB logic */ } |
| 177 | + public void sendEmail(User user) { /* Email logic */ } |
| 178 | + public void validateUser(User user) { /* Validation logic */ } |
| 179 | +} |
| 180 | + |
| 181 | +// GOOD: Single responsibility |
| 182 | +public class UserRepository { |
| 183 | + public void save(User user) { /* Only DB operations */ } |
| 184 | +} |
| 185 | + |
| 186 | +public class EmailService { |
| 187 | + public void sendWelcomeEmail(User user) { /* Only email logic */ } |
| 188 | +} |
| 189 | + |
| 190 | +public class UserValidator { |
| 191 | + public boolean validate(User user) { /* Only validation logic */ } |
| 192 | +} |
| 193 | +``` |
| 194 | + |
| 195 | +### Open/Closed Principle (OCP) |
| 196 | +Classes should be open for extension but closed for modification. |
| 197 | + |
| 198 | +```java |
| 199 | +// Using Strategy pattern to follow OCP |
| 200 | +public interface DiscountStrategy { |
| 201 | + double calculateDiscount(double amount); |
| 202 | +} |
| 203 | + |
| 204 | +public class RegularCustomerDiscount implements DiscountStrategy { |
| 205 | + @Override |
| 206 | + public double calculateDiscount(double amount) { |
| 207 | + return amount * 0.05; // 5% discount |
| 208 | + } |
| 209 | +} |
| 210 | + |
| 211 | +public class PremiumCustomerDiscount implements DiscountStrategy { |
| 212 | + @Override |
| 213 | + public double calculateDiscount(double amount) { |
| 214 | + return amount * 0.15; // 15% discount |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +public class OrderProcessor { |
| 219 | + public double processOrder(double amount, DiscountStrategy strategy) { |
| 220 | + double discount = strategy.calculateDiscount(amount); |
| 221 | + return amount - discount; |
| 222 | + } |
| 223 | +} |
| 224 | +``` |
| 225 | + |
| 226 | +### Liskov Substitution Principle (LSP) |
| 227 | +Objects should be replaceable with instances of their subtypes without altering program correctness. |
| 228 | + |
| 229 | +```java |
| 230 | +public abstract class Bird { |
| 231 | + public abstract void eat(); |
| 232 | + public abstract void makeSound(); |
| 233 | +} |
| 234 | + |
| 235 | +public class Sparrow extends Bird { |
| 236 | + @Override |
| 237 | + public void eat() { |
| 238 | + System.out.println("Sparrow eats seeds"); |
| 239 | + } |
| 240 | + |
| 241 | + @Override |
| 242 | + public void makeSound() { |
| 243 | + System.out.println("Chirp chirp"); |
| 244 | + } |
| 245 | + |
| 246 | + public void fly() { |
| 247 | + System.out.println("Sparrow flies"); |
| 248 | + } |
| 249 | +} |
| 250 | + |
| 251 | +// Any Bird reference can be replaced with Sparrow |
| 252 | +Bird bird = new Sparrow(); |
| 253 | +bird.eat(); // Works correctly |
| 254 | +``` |
| 255 | + |
| 256 | +### Interface Segregation Principle (ISP) |
| 257 | +Clients shouldn't be forced to depend on interfaces they don't use. |
| 258 | + |
| 259 | +```java |
| 260 | +// BAD: Fat interface |
| 261 | +public interface Worker { |
| 262 | + void work(); |
| 263 | + void eat(); |
| 264 | + void sleep(); |
| 265 | +} |
| 266 | + |
| 267 | +// GOOD: Segregated interfaces |
| 268 | +public interface Workable { |
| 269 | + void work(); |
| 270 | +} |
| 271 | + |
| 272 | +public interface Eatable { |
| 273 | + void eat(); |
| 274 | +} |
| 275 | + |
| 276 | +public interface Sleepable { |
| 277 | + void sleep(); |
| 278 | +} |
| 279 | + |
| 280 | +public class Human implements Workable, Eatable, Sleepable { |
| 281 | + @Override |
| 282 | + public void work() { /* implementation */ } |
| 283 | + |
| 284 | + @Override |
| 285 | + public void eat() { /* implementation */ } |
| 286 | + |
| 287 | + @Override |
| 288 | + public void sleep() { /* implementation */ } |
| 289 | +} |
| 290 | + |
| 291 | +public class Robot implements Workable { |
| 292 | + @Override |
| 293 | + public void work() { /* implementation */ } |
| 294 | + // Robot doesn't need to eat or sleep |
| 295 | +} |
| 296 | +``` |
| 297 | + |
| 298 | +### Dependency Inversion Principle (DIP) |
| 299 | +High-level modules shouldn't depend on low-level modules. Both should depend on abstractions. |
| 300 | + |
| 301 | +```java |
| 302 | +// BAD: High-level class depends on low-level class |
| 303 | +public class OrderService { |
| 304 | + private MySQLDatabase database; // Direct dependency |
| 305 | + |
| 306 | + public void saveOrder(Order order) { |
| 307 | + database.save(order); |
| 308 | + } |
| 309 | +} |
| 310 | + |
| 311 | +// GOOD: Both depend on abstraction |
| 312 | +public interface Database { |
| 313 | + void save(Order order); |
| 314 | +} |
| 315 | + |
| 316 | +public class OrderService { |
| 317 | + private Database database; // Depends on abstraction |
| 318 | + |
| 319 | + public OrderService(Database database) { |
| 320 | + this.database = database; |
| 321 | + } |
| 322 | + |
| 323 | + public void saveOrder(Order order) { |
| 324 | + database.save(order); |
| 325 | + } |
| 326 | +} |
| 327 | + |
| 328 | +public class MySQLDatabase implements Database { |
| 329 | + @Override |
| 330 | + public void save(Order order) { |
| 331 | + // MySQL specific implementation |
| 332 | + } |
| 333 | +} |
| 334 | +``` |
| 335 | + |
| 336 | +**Spring Relevance**: This is the foundation of Spring's Dependency Injection! |
| 337 | + |
| 338 | +## 🎯 Spring Framework Connections |
| 339 | + |
| 340 | +### 1. Bean Definition and Lifecycle |
| 341 | +Spring beans are Java objects managed by the IoC container, following OOP principles: |
| 342 | + |
| 343 | +```java |
| 344 | +@Component |
| 345 | +public class UserService { |
| 346 | + private final UserRepository userRepository; |
| 347 | + |
| 348 | + // Constructor injection following DIP |
| 349 | + public UserService(UserRepository userRepository) { |
| 350 | + this.userRepository = userRepository; |
| 351 | + } |
| 352 | + |
| 353 | + public User createUser(String username, String email) { |
| 354 | + // Business logic encapsulated |
| 355 | + User user = new User(username, email); |
| 356 | + return userRepository.save(user); |
| 357 | + } |
| 358 | +} |
| 359 | +``` |
| 360 | + |
| 361 | +### 2. Interface-Based Design |
| 362 | +Spring heavily uses interfaces for loose coupling: |
| 363 | + |
| 364 | +```java |
| 365 | +public interface UserService { |
| 366 | + User findById(Long id); |
| 367 | + User save(User user); |
| 368 | +} |
| 369 | + |
| 370 | +@Service |
| 371 | +public class UserServiceImpl implements UserService { |
| 372 | + // Implementation details hidden |
| 373 | +} |
| 374 | +``` |
| 375 | + |
| 376 | +## ⚠️ Common Pitfalls |
| 377 | + |
| 378 | +1. **God Classes**: Avoid classes that do too much |
| 379 | +2. **Tight Coupling**: Always program to interfaces |
| 380 | +3. **Inheritance Overuse**: Favor composition over inheritance |
| 381 | +4. **Breaking Encapsulation**: Avoid public fields |
| 382 | + |
| 383 | +## 🏃♂️ Practice Exercises |
| 384 | + |
| 385 | +1. Design a simple e-commerce system using all four OOP pillars |
| 386 | +2. Refactor a monolithic class to follow SOLID principles |
| 387 | +3. Create a payment processing system using polymorphism |
| 388 | +4. Implement a logging framework using the Template Method pattern |
| 389 | + |
| 390 | +## 📖 Further Reading |
| 391 | + |
| 392 | +- Effective Java by Joshua Bloch (Items 15-24) |
| 393 | +- Clean Code by Robert Martin (Chapter 6: Objects and Data Structures) |
| 394 | +- Design Patterns: Elements of Reusable Object-Oriented Software |
| 395 | + |
| 396 | +--- |
| 397 | +**Next Module**: [Collections Framework](../module2-collections/README.md) |
0 commit comments