Top Interview Questions
Object-Oriented Programming (OOPs) is a programming paradigm that uses the concept of “objects” to design and structure software. Unlike traditional procedural programming, which emphasizes functions and logic, OOPs focuses on data encapsulation, abstraction, inheritance, and polymorphism, enabling developers to build modular, reusable, and scalable software systems.
The object-oriented approach mirrors the real world by representing software entities as objects with attributes (properties) and behaviors (methods). This paradigm has become the foundation for modern programming languages such as Java, C++, Python, C#, Ruby, and Swift, enabling developers to handle complex software systems efficiently.
Object-Oriented Programming is a programming model in which data and functions are grouped together into objects. Each object represents a real-world entity and contains:
Attributes (Properties or Fields): Describe the characteristics of the object.
Example: A Car object might have attributes like color, model, and speed.
Methods (Functions): Define the behaviors or actions of the object.
Example: The Car object may have methods like start(), accelerate(), and brake().
OOPs aims to reduce complexity, improve code reusability, and simplify maintenance, making it a preferred choice for large-scale software development.
OOPs is built on four core concepts, often referred to as the four pillars of OOP:
Encapsulation is the practice of bundling data (attributes) and methods (functions) together within a class while restricting direct access from outside. This protects the integrity of the data by exposing only necessary operations through methods.
Benefits:
Data security and privacy
Prevents accidental modification
Simplifies maintenance
Example:
A BankAccount class may have a private balance attribute and a public deposit() method to update it safely.
Abstraction involves hiding complex implementation details and showing only the essential features of an object. It helps programmers focus on what an object does rather than how it does it.
Benefits:
Reduces complexity
Improves code readability
Supports modular programming
Example:
A Car object can have a drive() method without exposing the internal engine mechanics.
Inheritance allows a class (child or subclass) to derive properties and methods from another class (parent or superclass). It promotes code reuse and hierarchical relationships between classes.
Benefits:
Code reusability
Logical organization of classes
Reduces redundancy
Example:
A Vehicle class can have common properties like speed and fuelType. The Car and Bike classes can inherit these properties and add specific features like numberOfDoors or helmetStorage.
Polymorphism means “many forms”, allowing objects to behave differently based on context. It enables a single interface or method to work with different types of objects.
Types of Polymorphism:
Compile-Time (Method Overloading): Same method name but different parameters.
Run-Time (Method Overriding): Subclass provides a specific implementation of a method defined in the parent class.
Benefits:
Flexibility in code
Simplifies interface design
Supports dynamic behavior
Example:
A Shape class can have a draw() method. Subclasses like Circle and Rectangle can implement draw() differently.
Beyond the core four pillars, OOPs includes other important principles:
Class: Blueprint or template for creating objects. Defines attributes and methods.
Object: Instance of a class. Represents a real-world entity.
Constructor: Special method to initialize objects.
Destructor: Special method to destroy objects and free memory.
Association, Aggregation, Composition: Different ways objects relate to each other.
OOPs offers numerous advantages over procedural programming:
Modularity: Code is organized into independent objects, making it easier to manage and debug.
Reusability: Classes and objects can be reused in multiple programs.
Scalability: OOPs supports large, complex systems that can evolve over time.
Maintainability: Changes in one part of the program do not affect other parts, reducing errors.
Real-World Modeling: Objects simulate real-world entities, making software more intuitive and relatable.
Security: Encapsulation and abstraction provide better data security.
While OOPs is powerful, it has some limitations:
Complexity: Can be difficult for beginners to grasp the concepts.
Memory Consumption: Objects can consume more memory than procedural code.
Overhead: Overuse of inheritance and polymorphism can slow down performance.
Learning Curve: Requires a shift in thinking from procedural programming.
Many modern programming languages are based on OOPs principles:
Java: Fully object-oriented and widely used for enterprise applications.
C++: Supports both procedural and object-oriented programming.
Python: Flexible and easy-to-learn OOPs features.
C#: Microsoft’s language for .NET applications.
Ruby: Focuses on simplicity and productivity with OOPs support.
Swift: Apple’s language for iOS development with strong OOPs support.
OOPs is used in almost every modern software application:
Desktop Applications: Microsoft Office, Adobe Photoshop.
Web Development: Websites and web apps using Django (Python), ASP.NET (C#).
Game Development: Unity and Unreal Engine use OOPs concepts extensively.
Banking Systems: Secure and modular financial software.
Embedded Systems: IoT devices often use OOPs for modularity and maintainability.
Simulation Systems: Traffic simulation, flight simulators, and scientific modeling.
Use encapsulation to protect class data.
Apply inheritance wisely; avoid deep hierarchies.
Favor composition over inheritance for flexible design.
Keep classes single-purpose (Single Responsibility Principle).
Use interfaces and abstract classes for flexible and extensible design.
OOPs continues to evolve with modern software development trends:
Integration with AI and ML: Object-oriented structures help in organizing AI/ML pipelines.
Cloud and Microservices: OOPs enables modular, reusable services.
Cross-Platform Development: Languages like C# and Python support OOPs in mobile, web, and desktop apps.
Enhanced Tools and Frameworks: IDEs and frameworks make OOPs development faster and more efficient.
Object-Oriented Programming is a cornerstone of modern software development. By organizing software into objects that model real-world entities, OOPs provides modularity, reusability, maintainability, and scalability. Its core principles—encapsulation, abstraction, inheritance, and polymorphism—allow developers to build complex systems efficiently while keeping code readable and secure.
Despite its learning curve and potential overhead, OOPs remains the preferred paradigm for enterprise applications, game development, web development, and many other domains. As software systems grow in complexity, OOPs continues to be indispensable for creating robust, flexible, and scalable applications.
Q1. What is Object-Oriented Programming (OOP)?
Answer:
"OOP is a programming paradigm based on the concept of 'objects,' which contain both data (attributes) and methods (functions). It focuses on organizing code to model real-world entities and their interactions."
Example: A Car object may have attributes like color and model and methods like start() and stop().
Q2. What is a class and an object?
Answer:
Class: A blueprint or template for creating objects.
Object: An instance of a class with specific values.
Example:
class Car:
def __init__(self, color, model):
self.color = color
self.model = model
my_car = Car("Red", "Toyota") # Object of Car class
Q3. What are the main features of OOP?
Answer:
Encapsulation: Bundling data and methods.
Abstraction: Hiding implementation details.
Inheritance: Reusing code from parent classes.
Polymorphism: Objects behaving differently in different contexts.
Q4. What is the difference between procedural and object-oriented programming?
Answer:
| Feature | Procedural | OOP |
|---|---|---|
| Approach | Function/Procedure-based | Object-based |
| Data | Separate from functions | Bundled with methods |
| Reusability | Low | High (via inheritance) |
| Abstraction | Limited | Supported via classes |
| Examples | C, Pascal | Java, C++, Python |
Q5. What is an object’s state and behavior?
Answer:
State: The values of its attributes at a particular time.
Behavior: The methods/functions it can perform.
Example: For a Dog object:
State: color = brown, breed = Labrador
Behavior: bark(), eat()
Q6. What is encapsulation in OOP?
Answer:
"Encapsulation is the practice of restricting direct access to some of an object’s components, usually via access modifiers (private, protected, public), and providing methods to interact with them."
Example in Python:
class Student:
def __init__(self, name):
self.__name = name # private variable
def get_name(self):
return self.__name
Q7. What are access modifiers?
Answer:
Public: Accessible everywhere.
Private: Accessible only within the class.
Protected: Accessible within the class and its subclasses.
Q8. Why is encapsulation important?
Answer:
Protects data from unauthorized access.
Provides controlled access through getter/setter methods.
Maintains code modularity and maintainability.
Q9. What is abstraction in OOP?
Answer:
"Abstraction is the process of hiding implementation details and showing only the functionality to the user."
Example:
A Car class may have a start() method. Users call start() without knowing the engine ignition mechanism.
Q10. How is abstraction achieved in OOP?
Answer:
Abstract classes: Classes with abstract methods that must be implemented by derived classes.
Interfaces (in Java/C#): Define methods without implementation, which classes must implement.
Q11. Difference between abstraction and encapsulation?
| Feature | Encapsulation | Abstraction |
|---|---|---|
| Purpose | Protect data | Hide implementation details |
| Implementation | Private/protected access modifiers | Abstract classes/interfaces |
| Focus | Data security | Functionality |
Q12. What is inheritance in OOP?
Answer:
"Inheritance allows a class (child) to acquire properties and behaviors of another class (parent), promoting code reuse."
Example:
class Vehicle:
def move(self):
print("Vehicle is moving")
class Car(Vehicle):
pass
c = Car()
c.move() # Inherited from Vehicle
Q13. What are the types of inheritance?
Answer:
Single Inheritance: One child inherits from one parent.
Multiple Inheritance: One child inherits from multiple parents (supported in Python).
Multilevel Inheritance: Chain of inheritance (grandparent → parent → child).
Hierarchical Inheritance: One parent has multiple children.
Hybrid Inheritance: Combination of multiple types.
Q14. Why is inheritance used?
Answer:
Reduces code duplication.
Promotes modularity and reusability.
Enables polymorphism.
Q15. Difference between class and subclass?
Class (Parent): Original blueprint providing functionality.
Subclass (Child): Inherits features and can extend or override them.
Q16. What is polymorphism in OOP?
Answer:
"Polymorphism means 'many forms'. In OOP, it allows objects to be treated as instances of their parent class while behaving differently."
Q17. What are types of polymorphism?
Compile-time (Method Overloading): Same method name, different parameters.
Run-time (Method Overriding): Child class provides specific implementation of parent’s method.
Example:
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def speak(self):
print("Bark")
a = Dog()
a.speak() # Output: Bark
Q18. Difference between overloading and overriding?
| Feature | Overloading | Overriding |
|---|---|---|
| Definition | Same method name, different parameters | Child modifies parent method |
| Polymorphism type | Compile-time | Run-time |
| Example | Java: add(int a, int b) vs add(double a, double b) |
Python: Dog.speak() overrides Animal.speak() |
Q19. Can Python support method overloading?
Answer:
"Python doesn’t support traditional method overloading but default parameters or variable arguments can achieve similar behavior."
Q20. What is operator overloading?
Answer:
*"Operator overloading allows operators like +, -, , etc., to have different behavior for user-defined objects."
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(1,2)
p2 = Point(3,4)
p3 = p1 + p2 # Operator overloading
Q21. What is the difference between object and class?
Class: Blueprint/Template.
Object: Instance of the class with actual values.
Q22. What is a constructor?
Answer:
"A constructor is a special method that initializes objects when created."
Example in Python:
class Car:
def __init__(self, model):
self.model = model
Q23. What is a destructor?
Answer:
"A destructor is a method that is called when an object is destroyed, used to free resources."
Q24. What is the difference between static and instance variables?
Instance variable: Unique to each object.
Static variable (class variable): Shared among all objects of the class.
Q25. Difference between instance method and static method?
Instance method: Access object attributes, needs object.
Static method: Doesn’t access object attributes, callable by class directly.
Q26. What is an abstract class?
"A class that cannot be instantiated and may have abstract methods that must be implemented by derived classes."
Q27. What is an interface?
"An interface defines methods without implementation that must be implemented by a class. (In Python, abstract base classes are used)"
Q28. Difference between abstract class and interface?
| Feature | Abstract Class | Interface |
|---|---|---|
| Implementation | Can have implemented methods | Only method signatures |
| Inheritance | Single/multi inheritance | Multiple inheritance supported |
| Object creation | Cannot instantiate | Cannot instantiate |
Q29. What is multiple inheritance?
"When a class inherits from more than one class. Supported in Python but not in Java (interfaces used instead)."
Q30. What is composition vs inheritance?
Inheritance: "Is-a" relationship (Dog is-an Animal).
Composition: "Has-a" relationship (Car has an Engine).
Q31. How would you implement a bank system in OOP?
Classes: Account, Customer, Transaction.
Methods: deposit(), withdraw(), transfer().
Attributes: balance, account_number, customer_name.
Q32. How do you model real-world objects in OOP?
"Identify entities, their attributes (state), and behaviors (methods), then define classes and objects accordingly."
Q33. What is the difference between shallow copy and deep copy?
Shallow copy: Copies object but references the same nested objects.
Deep copy: Creates independent copies of nested objects.
Q34. How do you achieve polymorphism in Python?
"Through method overriding, operator overloading, or duck typing."
Q35. How do you prevent a class from being inherited?
"In Python, use final decorator (Python 3.8+) or design pattern conventions. In Java/C++, use final keyword."
Q36. How do you prevent method overriding?
"Declare the method as final in Java/C++ or use naming conventions in Python."
Q37. How would you handle multiple types of users in a system (Admin, Guest, Member)?
Create a base class User with common attributes and methods.
Create subclasses Admin, Guest, Member with specific behavior.
Q38. Explain diamond problem in multiple inheritance.
"Occurs when a class inherits from two classes that have a common parent. Python solves this with Method Resolution Order (MRO)."
Q39. Difference between association, aggregation, and composition?
| Type | Relationship | Lifetime |
|---|---|---|
| Association | Uses another object | Independent |
| Aggregation | "Has-a", shared ownership | Part can exist independently |
| Composition | "Has-a", strong ownership | Part destroyed with whole |
Q40. What is coupling and cohesion?
Coupling: Degree of interdependence between modules (low coupling preferred).
Cohesion: Degree to which elements of a module belong together (high cohesion preferred).
Q41. How is OOP beneficial over procedural programming?
Code reuse via inheritance.
Data security via encapsulation.
Easier maintenance and modularity.
Models real-world entities better.
Q42. Difference between class variable and instance variable?
Class variable: Shared across all objects.
Instance variable: Unique to each object.
Q43. Can a constructor be private? Why?
"Yes, to restrict object creation outside the class (used in Singleton pattern)."
Q44. What is the singleton pattern?
"Design pattern that restricts a class to only one instance and provides a global access point."
Q45. Difference between object-oriented design and object-oriented programming?
OOP: Implementation using programming languages.
OOD: Designing system architecture using OOP concepts.
Answer:
OOP (Object-Oriented Programming) is a programming paradigm based on objects, which are instances of classes. Objects encapsulate data (attributes) and behavior (methods).
Importance:
Code reusability via inheritance
Modular structure through encapsulation
Easy maintenance and scalability
Supports polymorphism for flexible code behavior
Answer:
Encapsulation: Hiding internal state; exposing only necessary behavior.
Example: Private variables with public getters/setters.
Abstraction: Hiding complexity and exposing only relevant functionality.
Example: Abstract classes or interfaces.
Inheritance: Creating a new class based on an existing class.
Example: class Car extends Vehicle.
Polymorphism: Objects taking multiple forms.
Example: Method overriding (runtime) or method overloading (compile-time).
Answer:
Class: Blueprint/template for objects; defines attributes and methods.
Object: Instance of a class; occupies memory.
"Class is a concept; object is a real-world entity."
Answer:
Encapsulation: Protects data from outside access; implemented using access modifiers.
Abstraction: Focuses on what an object does, not how; implemented using abstract classes or interfaces.
Answer:
| Feature | Overloading | Overriding |
|---|---|---|
| Definition | Same method name, different parameters | Subclass provides implementation for parent method |
| Compile/Run-time | Compile-time (static) | Runtime (dynamic) |
| Access Modifier | Can vary | Cannot reduce visibility |
| Example | add(int a, int b) vs add(int a, int b, int c) |
void display() in parent vs child |
Answer:
Multiple inheritance: A class inherits from multiple classes.
C++: Supported.
Java/C#: Not directly supported; use interfaces.
Answer:
Polymorphism: Ability of an object to behave differently depending on context.
Compile-time: Method overloading
int add(int a, int b)
int add(int a, int b, int c)
Runtime: Method overriding
class Animal { void sound(){System.out.println("Animal sound");} }
class Dog extends Animal { void sound(){System.out.println("Bark");} }
Animal a = new Dog(); a.sound(); // Prints Bark
Answer:
| Feature | Interface | Abstract Class |
|---|---|---|
| Methods | Only abstract (Java 8+ allows default/static) | Abstract + concrete |
| Variables | Final/static | Can be normal |
| Inheritance | Multiple allowed | Single class inheritance (Java) |
| Usage | Contracts | Partial implementation |
Answer:
Constructor: Special method invoked when object is created; used to initialize.
Destructor: Cleans up before object is destroyed (C++/Python __del__).
Example:
class Employee { Employee(){ System.out.println("Employee created"); } }
Answer:
Static: Belongs to class; shared across objects; memory-efficient.
Instance: Belongs to object; each object has its own copy.
Answer:
Aggregation: Has-a relationship; object can exist independently.
Example: Department has Employees.
Composition: Stronger Has-a; child cannot exist without parent.
Example: Car has Engine. If car destroyed, engine destroyed.
Answer:
Shallow copy: Copies references; objects share inner objects.
Deep copy: Copies objects and nested objects; independent.
Answer:
Child class defines a static method with same name as parent; parent’s method is hidden, not overridden.
Differs from overriding which is runtime polymorphism.
Answer:
final: Keyword to prevent inheritance or method overriding.
finally: Block executed after try/catch.
finalize(): Method called before garbage collection (Java).
Answer:
Inner class: Non-static; has access to outer class members.
Nested class: Static; does not require outer object.
Answer:
S: Single Responsibility – class should have one reason to change
O: Open/Closed – open for extension, closed for modification
L: Liskov Substitution – subclass can replace superclass without breaking code
I: Interface Segregation – many small interfaces better than one big
D: Dependency Inversion – depend on abstractions, not concretes
Answer:
Association: Objects know each other; long-lived relation.
Dependency: One object uses another temporarily.
Answer:
Creation – constructor called
Usage – object methods invoked
Destruction – garbage collection/destructor
Answer:
Call multiple methods on same object in a single statement.
obj.setName("John").setAge(30).printDetails();
Answer:
Static (compile-time): Method overloading, early binding
Dynamic (runtime): Method overriding, late binding
Answer:
Ensures only one instance of a class exists.
Example in Java:
class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null) instance = new Singleton();
return instance;
}
}
Answer:
Creates objects without exposing instantiation logic
Useful when creating objects of multiple types through one interface
Answer:
Defines a one-to-many dependency.
Example: Event listeners in GUI frameworks.
Answer:
MVC: Model-View-Controller; user interaction separated from UI
MVVM: Model-View-ViewModel; commonly used in WPF, data-binding supported
Answer:
Remove references for garbage collection
Avoid circular references
Use weak references if applicable
Answer:
Inheritance: Is-a relationship; promotes code reuse
Composition: Has-a relationship; more flexible, avoids tight coupling
Answer:
Dynamically adds behavior to objects without altering class
Example: Adding filters to streams in Java
Answer:
Converts one interface to another expected by client
Example: Legacy code integration
Answer:
Factory Method: Creates one family of objects
Abstract Factory: Creates families of related objects
Answer:
Use centralized logging classes (singleton)
Example frameworks: Log4j, SLF4J
Ensures maintainability and consistency
Answer:
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
double radius;
double area(){ return Math.PI * radius * radius; }
}
class Rectangle extends Shape {
double length, width;
double area(){ return length*width; }
}
Demonstrates inheritance, abstraction, and polymorphism
Answer:
Use try-catch blocks
Specific exceptions first, generic later
Example in Java:
try{ ... }
catch(IOException e){ ... }
catch(Exception e){ ... }
Answer:
Use polymorphism and interfaces
Example: Interface AccessControl, classes Admin, User with different methods
Answer:
Use interfaces or abstract classes
Load dynamically at runtime using reflection or dependency injection
Answer:
clone() can perform shallow copy
For deep copy, manually copy nested objects
Answer:
Preconditions, postconditions, invariants
Example: Method checks input validity, ensures expected state
Answer:
class Box<T> {
private T item;
public void set(T item){ this.item=item; }
public T get(){ return item; }
}
Enables type-safe, reusable classes
Answer:
Define event source class
Use listener interfaces
Subscribe handlers to events
Answer:
Converting objects to byte stream for storage or transfer
Deserialization restores object
Example: Java Serializable interface
Answer:
Use interfaces for backward compatibility
Maintain multiple implementations
Ensure API contracts are not broken
Answer:
"In a payroll system, SRP: separate Employee and Payroll processing; OCP: new tax rules added via new classes; LSP: Manager extends Employee without breaking functionality; ISP: separate interfaces for Payroll and Benefits; DIP: PayrollService depends on IPaymentGateway interface."