Object-Oriented Programming concepts: encapsulation, inheritance, polymorphism, abstraction, and design patterns.
5 Questions Detailed Answers
1Explain the 4 pillars of OOP.
Easy
View Answer
Encapsulation: bundling data + methods, hiding internal state (private fields, public getters). Inheritance: class inherits properties/methods from parent (code reuse). Polymorphism: same interface, different implementations (method overloading = compile-time, overriding = runtime). Abstraction: hiding complexity, showing only essentials (abstract classes, interfaces).
2What is the difference between composition and inheritance?
Medium
View Answer
Inheritance: "is-a" relationship (Dog is-a Animal). Tight coupling, fragile base class problem. Composition: "has-a" relationship (Car has-a Engine). Loose coupling, more flexible. Prefer composition over inheritance — it's easier to change behavior at runtime and avoids deep hierarchies.
3What are design patterns? Name 3 commonly used ones.
Medium
View Answer
Design patterns are reusable solutions to common problems. (1) Singleton: one instance globally (DB connection). (2) Factory: create objects without specifying exact class. (3) Observer: notify multiple objects of state changes (event systems). Others: Strategy, Decorator, Adapter, Builder.
4What is method overloading vs method overriding?
Easy
View Answer
Overloading (compile-time polymorphism): same method name, different parameters in the SAME class. `add(int a, int b)` vs `add(double a, double b)`. Overriding (runtime polymorphism): same method signature in PARENT and CHILD class. Child replaces parent's implementation. Requires inheritance.
5Explain the Singleton pattern and its thread-safe implementation.
Hard
View Answer
Singleton ensures only one instance exists. Thread-safe approaches: (1) Eager initialization: create at class load. (2) Double-checked locking: `if(instance==null) synchronized(class) { if(instance==null) instance = new Singleton(); }`. (3) Bill Pugh: static inner class holder. (4) Enum Singleton (Java) — simplest and safest.