Object Oriented Programming
OOP
Contents
Basic Question .............................................................................................................. 2
ENCAPSULATION:.................................................................................................. 4
INHERITANCE: ....................................................................................................... 4
POLYMORPHISM: .................................................................................................. 5
ABSTRACTION: ...................................................................................................... 5
Intermediate Level Question .......................................................................................... 7
MEMORY MANAGEMENT AND OBJECT LIFECYCLE.......................................... 8
DESIGN CONCEPTS................................................................................................ 8
Advance Level Question ................................................................................................ 8
DESIGN PATTERNS: ............................................................................................... 9
Language-Specific Questions ....................................................................................... 11
JAVA-SPECIFIC ..................................................................................................... 11
C++-SPECIFIC ....................................................................................................... 11
PYTHON-SPECIFIC .............................................................................................. 11
Design-Pattern Questions ............................................................................................ 12
CREATIONAL PATTERNS ..................................................................................... 12
STRUCTURAL PATTERNS .................................................................................... 12
BEHAVIOUR PATTERNS ....................................................................................... 12
Additional Questions ................................................................................................... 13
MODERN OOP CONCEPTS ................................................................................... 13
Testing and OOP ..................................................................................................... 13
Performance Considerations .................................................................................... 13
Basic Question
Q1: What is Object-Oriented Programming?
Object-Oriented Programming is a programming paradigm based on the concept of "objects"
which contain data (attributes) and code (methods). It organizes software design around data, or
objects, rather than functions and logic.
Q2: Why do we need OOP?
OOP helps us to think in terms of Real-World Projects. What does a hospital have?
• Patient (name, address, doctor who will treat)
• Doctor (name)
Q3: What are the important pillars of OOP?
• Abstraction: show only what is necessary
• Polymorphism: Object acts differently under different conditions. (user object can
become an employee, admin etc)
• Inheritance: Parent Child Relationship
• Encapsulation: Hide complexity
APIE
Q4: What is a class and object?
A class is a user-defined blueprint for creating objects. It encapsulates data members
(variables) and member functions (methods) that operate on the data.
An object is an instance of a class. It is created using the class and can access the class's
methods and variables.
Q5: What is the difference between a Class and an Object?
• Class is a template/blueprint; Object is an instance of that template
• Class doesn't allocate memory; Object allocates memory when created
• Class is declared once; Multiple objects can be created from one class
• Class defines structure; Object contains actual data
ENCAPSULATION:
Q6: What is Encapsulation?
Encapsulation is the bundling of data and methods that operate on that data within a single unit
(class), and restricting direct access to some of the object's components. It's achieved through
access modifiers.
Q7: What are Access Modifiers?
Access modifiers control the visibility and accessibility of class members:
• Public: Accessible from anywhere
• Private: Accessible only within the same class
• Protected: Accessible within the class and its subclasses
• Package/Default: Accessible within the same package
Q8: What are Getters and Setters?
Getters and setters are methods used to access and modify private attributes of a class. They
provide controlled access to class data and enable validation before setting values.
INHERITANCE:
Q9: What is Inheritance?
Inheritance is a mechanism where a new class (child/derived class) inherits properties and
behaviors from an existing class (parent/base class), promoting code reusability.
Q10: What are the types of Inheritance?
• Single Inheritance: One child class inherits from one parent class
• Multiple Inheritance: One child class inherits from multiple parent classes
• Multilevel Inheritance: Chain of inheritance (A→B→C)
• Hierarchical Inheritance: Multiple child classes inherit from one parent
• Hybrid Inheritance: Combination of multiple inheritance types
Q11: What is the difference between IS-A and HAS-A relationships?
• IS-A (Inheritance): "Car IS-A Vehicle" - represents inheritance relationship
• HAS-A (Composition): "Car HAS-A Engine" - represents composition/aggregation
relationship
Feature Aggregation Composition
Type of Relationship "Has-a" (weak ownership) "Owns-a"(strong ownership)
Lifespan Contained object can live | Contained object dies with
independently of the the container
container
Dependency Loose coupling Strong coupling
Real-world Example A `Team` has `Players` A `House` has `Rooms`
(but players can exist (rooms don’t make sense
without team) without a house)
Memory Management Usually passed as a pointer Usually created inside the
or reference. containing class.
POLYMORPHISM:
Q12: What is Polymorphism?
Polymorphism allows objects of different classes to be treated as objects of a common base class
while maintaining their specific behaviors. It enables one interface to represent different
underlying forms.
Q13: What are the types of Polymorphism?
• Compile-time Polymorphism (Static): Method overloading, operator overloading
• Runtime Polymorphism (Dynamic): Method overriding, virtual functions
Q14: What is Method Overloading?
Method overloading allows multiple methods with the same name but different parameters
(number, type, or order) within the same class.
Q15: What is Method Overriding?
Method overriding allows a subclass to provide a specific implementation of a method that is
already defined in its parent class.
ABSTRACTION:
Q16: What is Abstraction?
Abstraction is the process of hiding complex implementation details while showing only
essential features of an object. It focuses on what an object does rather than how it does it.
An abstract method is a method that is declared but not implemented
A concrete method is a regular method that has a full implementation (a body with code).
Q17: What is the difference between Abstract Class and Interface?
Python and C++ do
allow multiple
inheritance, even
• Abstract Class: Can have both abstract and concrete methods, can have instance
with abstract classes. variables, supports single inheritance
But Java and C# are
more restrictive—this
• Interface: Only abstract methods (traditionally), cannot have instance variables, supports
line is mainly true for
those.
multiple inheritance
Q18: Differentiate between abstraction and encapsulation.
• Abstraction: Show only what is necessary
• Encapsulation: hide complexity
Feature Abstraction Encapsulation
What it is Hiding implementation details, rapping data and methods into a
showing only essential features single unit (class) and restricting
direct access
purpose Reduce complexity and expose Protect data from unauthorized access
only relevant operations
Achieved by Using abstract classes, interfaces, Using access specifiers (private,
and function hiding public, etc.)
Focus On how data is accessed and
On what an object does
protected
Code #include <iostream> #include <iostream>
using namespace std; using namespace std;
// Abstract class class BankAccount {
class Shape { private:
public: double balance; // private = can't access directly
virtual void draw() = 0; // Pure virtual from outside
function = interface
}; public:
void deposit(double amount) {
class Circle : public Shape { if (amount > 0) balance += amount;
public: }
void draw() override {
cout << "Drawing a Circle\n"; void withdraw(double amount) {
} if (amount > 0 && amount <= balance) balance
}; -= amount;
}
int main() {
Shape* s = new Circle(); double getBalance() {
s->draw(); // Only need to know about return balance;
draw(), not internal drawing logic }
delete s; };
return 0;
} int main() {
BankAccount acc;
acc.deposit(1000);
acc.withdraw(300);
cout << "Current Balance: $" << acc.getBalance()
<< endl;
return 0;
}
Intermediate Level Question
Q19: What is Composition vs Inheritance?
• Composition: "HAS-A" relationship, objects contain other objects
• Inheritance: "IS-A" relationship, classes inherit from other classes
• Composition is often preferred as it's more flexible and doesn't break encapsulation
Q20: What is Aggregation vs Composition?
• Aggregation: Weak relationship, objects can exist independently
• Composition: Strong relationship, contained objects cannot exist without container
Q21: What is a Constructor?
A constructor is a special method automatically called when an object is created. It initializes the
object's state and allocates memory.
Q22: What are the types of Constructors?
• Default Constructor: No parameters, provides default initialization
• Parameterized Constructor: Takes parameters for custom initialization
• Copy Constructor: Creates object as copy of another object
Q23: What is a Destructor?
A destructor is a special method called when an object is destroyed or goes out of scope. It's used
to release resources and perform cleanup operations.
Q24: What is Method Binding?
• Static Binding (Early Binding): Method calls resolved at compile time
• Dynamic Binding (Late Binding): Method calls resolved at runtime based on object type
Q25: What are Virtual Functions?
Virtual functions enable runtime polymorphism by allowing derived classes to override base
class methods. The correct method is called based on the actual object type.
Q26: What is an Abstract Method?
An abstract method is a method declared without implementation. Classes containing abstract
methods become abstract classes and cannot be instantiated.
MEMORY MANAGEMENT AND OBJECT LIFECYCLE
Q27: What is Object Lifecycle?
Object lifecycle includes: Creation (instantiation) → Initialization (constructor) → Usage →
Destruction (destructor) → Garbage collection
Q28: What is Garbage Collection?
Garbage collection is automatic memory management that deallocates memory occupied by
objects that are no longer referenced or reachable.
Q29: What is the difference between Stack and Heap memory?
• Stack: Stores local variables and method calls, faster access, limited size
• Heap: Stores objects and dynamic data, slower access, larger size
DESIGN CONCEPTS
Q30: What is Coupling and Cohesion?
• Coupling: Degree of interdependence between modules (aim for loose coupling)
• Cohesion: Degree to which elements within a module belong together (aim for high
cohesion)
Q31: What is the Liskov Substitution Principle?
Objects of a superclass should be replaceable with objects of its subclasses without breaking the
application functionality.
Q32: What is the Open/Closed Principle?
Software entities should be open for extension but closed for modification. You should be able to
add new functionality without changing existing code.
Advance Level Question
Q33: What is Diamond Problem in Multiple Inheritance?
Diamond problem occurs when a class inherits from two classes that have a common base class,
creating ambiguity about which parent's method to inherit.
Q34: How do you resolve Diamond Problem?
Solutions include:
• Virtual inheritance
• Interface segregation
• Composition over inheritance
• Explicit method resolution
Q35: What is Metaclass?
A metaclass is a class whose instances are classes themselves. It defines how classes are
constructed and behave.
Q36: What is Reflection?
Reflection is the ability of a program to examine and modify its own structure and behavior at
runtime, including inspecting classes, methods, and properties.
Q37: What is Serialization?
Serialization is the process of converting an object into a format that can be stored or transmitted
and later reconstructed.
Q38: What are Inner Classes?
Inner classes are classes defined within another class. Types include:
• Static nested classes
• Non-static inner classes
• Local classes
• Anonymous classes
Q39: What is Method Chaining?
Method chaining is a technique where multiple method calls are linked together in a single
statement by returning the object itself from each method.
DESIGN PATTERNS:
Q40: What is Singleton Pattern?
Singleton pattern ensures a class has only one instance and provides global access to that
instance.
Q41: What is Factory Pattern?
Factory pattern creates objects without specifying their exact classes, using a common interface
or base class.
Q42: What is Observer Pattern?
Observer pattern defines a one-to-many dependency between objects, where changes in one
object notify all dependent objects.
Q43: What is Strategy Pattern?
Strategy pattern defines a family of algorithms, encapsulates each one, and makes them
interchangeable at runtime.
Q44: What is Decorator Pattern?
Decorator pattern allows adding new functionality to objects dynamically without altering their
structure.
SOLID PRINCIPLES:
Q45: What are SOLID Principles?
• S - Single Responsibility: Class should have only one reason to change
• O - Open/Closed: Open for extension, closed for modification
• L - Liskov Substitution: Subtypes must be substitutable for base types
• I - Interface Segregation: Clients shouldn't depend on unused interfaces
• D - Dependency Inversion: Depend on abstractions, not concretions
Q46: Explain Dependency Injection.
Dependency Injection is a technique where dependencies are provided to an object rather than
the object creating them itself, promoting loose coupling.
Language-Specific Questions
JAVA-SPECIFIC
Q46: What is the difference between == and equals() in Java?
• == compares references (memory addresses)
• equals() compares actual content/values
Q47: What is the difference between String, StringBuilder, and StringBuffer?
• String: Immutable
• StringBuilder: Mutable, not thread-safe, faster
• StringBuffer: Mutable, thread-safe, slower
Q48: What is autoboxing and unboxing?
• Autoboxing: Automatic conversion of primitive types to wrapper classes
• Unboxing: Automatic conversion of wrapper classes to primitive types
C++-SPECIFIC
Q49: What is multiple inheritance in C++?
C++ supports multiple inheritance where a class can inherit from multiple base classes, unlike
Java which uses interfaces for similar functionality.
Q50: What are virtual destructors?
Virtual destructors ensure proper cleanup in inheritance hierarchies by calling the correct
destructor when deleting objects through base class pointers.
PYTHON-SPECIFIC
Q51: What is the difference between str and repr?
• str: Human-readable representation for end users
• repr: Unambiguous representation for developers/debugging
Q52: What is Method Resolution Order (MRO)?
MRO determines the order in which methods are inherited in multiple inheritance scenarios,
following C3 linearization algorithm.
Design-Pattern Questions
CREATIONAL PATTERNS
Q53: Compare Singleton vs Factory Pattern.
• Singleton: Controls instance creation (only one instance)
• Factory: Controls object creation (multiple instances of different types)
Q54: What is Abstract Factory Pattern?
Abstract Factory provides an interface for creating families of related objects without specifying
their concrete classes.
Q55: What is Builder Pattern?
Builder pattern constructs complex objects step by step, allowing different representations of the
same construction process.
STRUCTURAL PATTERNS
Q56: What is Adapter Pattern?
Adapter pattern allows incompatible interfaces to work together by wrapping an existing class
with a new interface.
Q57: What is Facade Pattern?
Facade pattern provides a simplified interface to a complex subsystem, hiding the complexity
from clients.
BEHAVIOUR PATTERNS
Q58: What is Command Pattern?
Command pattern encapsulates requests as objects, allowing parameterization of clients with
different requests and queuing operations.
Q59: What is State Pattern?
State pattern allows an object to change its behavior when its internal state changes, appearing as
if the object changed its class.
Additional Questions
MODERN OOP CONCEPTS
Q71: What are Mixins?
Mixins are classes that provide methods to other classes through inheritance, promoting code
reuse without traditional inheritance relationships.
Q72: What is Composition over Inheritance principle?
Favor object composition over class inheritance to achieve more flexible and maintainable code.
Q73: What are Immutable Objects?
Objects whose state cannot be modified after creation, providing thread safety and predictable
behavior.
Q74: What is Lazy Initialization?
Delaying object creation or expensive operations until they're actually needed, improving
performance.
Q75: What are Data Transfer Objects (DTOs)?
Simple objects used to transfer data between layers or systems, typically containing only data
without business logic.
Testing and OOP
Q76: How does OOP facilitate unit testing?
OOP enables better testing through encapsulation, dependency injection, and mock objects.
Q77: What is Test-Driven Development (TDD) in OOP context?
Writing tests before implementation, ensuring code meets requirements and maintains quality.
Performance Considerations
Q78: What are the performance implications of OOP?
Object-Oriented Programming improves modularity and reusability but comes with certain
performance trade-offs:
1. Virtual Function Calls
• Virtual functions use v-tables (virtual tables), which add indirection.
• Calls are resolved at runtime (dynamic dispatch), making them slower than non-virtual
(static) calls.
• Can break inlining and reduce performance.
2. Memory Overhead
• Objects may have extra space for v-table pointers, metadata, etc.
• Small objects in large numbers (like particles in a game) can cause significant overhead.
3. Cache Locality
• OOP encourages heap allocations and pointer-based structures, which scatter objects
in memory.
• Poor cache locality → more cache misses, slower access.
4. Optimization Challenges
• OOP features like polymorphism make it harder for compilers to optimize code (e.g.,
inlining, branch prediction).
• Overuse of abstraction may obscure optimization opportunities.
Q79: How do you optimize OOP code?
Here are practical ways to improve performance in OOP:
1. Prefer Composition over Inheritance
• Avoid deep inheritance chains that complicate design and slow virtual calls.
• Composition gives more flexibility and better cache use.
2. Minimize Virtual Function Use
• Use virtual functions only when needed.
• Prefer final, static, or non-virtual functions where possible.
• Devirtualization is possible with final or override.
3. Efficient Memory Management
• Avoid frequent heap allocations.
• Use object pooling, memory arenas, or stack allocation when possible.
4. Use Value Semantics Where Possible
• Favor small objects stored by value (on the stack) to reduce heap overhead.
5. Use Data-Oriented Design (DOD) Techniques
• Group data that is used together to improve cache locality.
• Flatten object hierarchies for tight memory layout.
Q80: What is Object Pooling?
Reusing objects instead of creating new ones to reduce garbage collection overhead and improve
performance.
Benefits:
• Reduces heap allocations and garbage collection pressure.
• Great for objects created/destroyed frequently (e.g., bullets in games, database
connections).
Example (Conceptual in C++):