What is dependency inversion principle (DIP)?
Why Interviewers Ask This
Mid-level OOP Concepts roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
The Dependency Inversion Principle (DIP) states: High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions. Violation of DIP: class UserController { // High-level private MySQLDatabase db = new MySQLDatabase(); // Depends on concrete low-level! private EmailService emailService = new SendGridEmailService(); // Concrete! public void registerUser(String email) { db.save(new User(email)); // Tightly coupled emailService.send(email, "Welcome!"); // Tightly coupled } } // Problems: can't test without MySQL and SendGrid, can't switch to PostgreSQL, // testing requires real infrastructure, hard to change implementations. DIP applied: // Abstractions (interfaces): interface UserRepository { void save(User user); } interface EmailNotifier { void sendWelcome(String email); } // High-level module depends on abstractions: class UserController { private final UserRepository repository; // Abstraction private final EmailNotifier notifier; // Abstraction public UserController(UserRepository repository, EmailNotifier notifier) { this.repository = repository; this.notifier = notifier; } public void registerUser(String email) { repository.save(new User(email)); notifier.sendWelcome(email); } } // Low-level modules implement abstractions: class MySQLUserRepository implements UserRepository { public void save(User user) { /* MySQL */ } } class SendGridEmailNotifier implements EmailNotifier { public void sendWelcome(String email) { /* SendGrid */ } } class MockUserRepository implements UserRepository { public void save(User user) { /* in-memory for testing */ } } // Injection: UserController ctrl = new UserController(new MySQLUserRepository(), new SendGridEmailNotifier()); // Testing: UserController testCtrl = new UserController(new MockUserRepository(), new MockNotifier());. DIP enables testability, flexibility, and loose coupling. It's the "D" in SOLID.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex OOP Concepts answers easy to follow.