OBJECT ORIENTED PROGRAMMING
OOP Basics
✅ 1. What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around objects rather than functions and logic. Objects represent real-world entities
with attributes (data) and behaviors (methods or functions).
OOP focuses on four key principles:
1. Encapsulation – Bundling data and methods.
2. Abstraction – Hiding unnecessary details.
3. Inheritance – Reusing and extending functionality.
4. Polymorphism – Using interfaces and overriding methods.
OOP makes code modular, reusable, and easier to maintain, enabling developers to model
complex systems effectively.
✅ 2. Difference between procedural programming and OOP
Feature Procedural Programming Object-Oriented Programming (OOP)
Focuses on functions or Focuses on objects that encapsulate
Approach
procedures data and behavior
Data is global and accessible Data is hidden and controlled via
Data handling
from anywhere objects
Inheritance and polymorphism allow
Code reuse Limited reuse
better reuse
Maintenance Harder to scale and maintain Easier to extend, modify, and debug
Example
C, Pascal Java, C++, Python (OOP features)
languages
✅ 3. What is an object? What is a class?
Class:
A blueprint or template that defines the structure and behavior of objects. It specifies
the attributes (variables) and methods (functions) that the objects created from the
class will have.
Object:
An instance of a class representing a specific entity with defined state and behavior. It
holds actual values in attributes and can perform operations through its methods.
Example:
If Car is a class, myCar with attributes like color, speed, and methods like accelerate() is an
object.
✅ 4. What are the advantages of OOP?
Modularity: Code is divided into classes and objects, making it easier to manage and
understand.
Reusability: Inheritance allows reuse of existing code without rewriting.
Scalability: Well-structured code can be extended to accommodate new features.
Maintainability: Easier debugging and updating due to encapsulated and modular
components.
Data security: Encapsulation restricts direct access to sensitive data.
Improved collaboration: Different developers can work on different objects without
affecting each other’s work.
✅ 5. What are access specifiers (public, private, protected)?
Access specifiers define the visibility and accessibility of class members (variables and
methods):
Public:
Members are accessible from anywhere, both inside and outside the class.
Private:
Members are accessible only within the class itself. This helps in hiding sensitive
information and controlling access.
Protected:
Members are accessible within the class and its derived classes but not from outside.
These specifiers help implement encapsulation by controlling how data and methods are
exposed.
✅ 6. Difference between instance variables and class variables
Feature Instance Variables Class Variables
Definition Variables unique to each object Variables shared across all instances of
Feature Instance Variables Class Variables
the class
Memory
Separate memory per object Single memory shared by all objects
Allocation
Accessed through the object Accessed through the class name or
Access
reference object reference
Store object-specific
Use case Store common data relevant to the class
information
Example:
For a Car class, color may be an instance variable, while totalCars could be a class variable
shared across all instances.
✅ 7. What is abstraction? What is encapsulation? How do they differ?
Abstraction:
The process of hiding unnecessary implementation details and showing only essential
features to the user. It helps in reducing complexity.
Encapsulation:
The process of wrapping data (variables) and methods (functions) together into a
single unit and restricting access to the internal state of the object using access
specifiers.
Difference:
Abstraction focuses on hiding complexity and showing relevant data, whereas
encapsulation is about protecting data and restricting unauthorized access.
Abstraction is achieved using interfaces or abstract classes, while encapsulation is
achieved using access modifiers.
Four Pillars of OOP
✅ Encapsulation
1. What is encapsulation?
Encapsulation is the concept of bundling data (attributes) and methods (functions) that
operate on that data into a single unit, i.e., a class. It restricts direct access to some of an
object's components by using access specifiers like private, protected, and public, thereby
enforcing controlled interaction with the object’s internal state.
2. How does encapsulation improve security?
Encapsulation improves security by hiding the internal details and sensitive data of an
object. By making attributes private and providing controlled access through methods
(getters and setters), it prevents unintended modifications and misuse, ensuring data
integrity and reducing the risk of bugs or vulnerabilities.
3. Example of encapsulation in real life
A bank account is a good example. The balance is hidden from direct access. Customers
cannot arbitrarily change it. Instead, they must use methods like deposit() or withdraw(),
which enforce rules (like balance checks), ensuring the account remains secure and
consistent.
✅ Inheritance
1. What is inheritance? Why do we use it?
Inheritance is a mechanism where one class (child or subclass) acquires properties and
behaviors from another class (parent or superclass). It promotes code reuse, reduces
redundancy, and helps create hierarchical relationships, allowing developers to build on
existing implementations efficiently.
2. Types of inheritance
1. Single inheritance:
A class inherits from one parent class.
2. Multiple inheritance:
A class inherits from more than one parent class.
3. Multilevel inheritance:
A class inherits from a child class, forming a chain of inheritance.
4. Hierarchical inheritance:
Multiple classes inherit from a single parent class.
5. Hybrid inheritance:
A combination of two or more inheritance types.
3. What is the difference between composition and inheritance?
Inheritance models an “is-a” relationship. Example: A Car is a Vehicle.
Composition models a “has-a” relationship. Example: A Car has an Engine.
Composition is preferred when tight coupling is not desirable, promoting flexibility and
easier maintenance.
4. What are the drawbacks of multiple inheritance? (Diamond problem)
The diamond problem occurs when a class inherits from two classes that both derive from a
common base class, leading to ambiguity about which path to follow or which method to
call. This can cause inconsistencies and complicate the design.
5. How is multiple inheritance handled in Java vs C++?
Java:
Java does not support multiple inheritance with classes to avoid the diamond
problem. Instead, it uses interfaces, which can be implemented by a class, allowing
multiple behavior inheritances without ambiguity.
C++:
C++ supports multiple inheritance directly, allowing a class to inherit from multiple
classes. It uses mechanisms like virtual inheritance to resolve ambiguities such as the
diamond problem.
✅ Polymorphism
1. What is polymorphism?
Polymorphism means “many forms.” It allows objects of different classes to be treated as
objects of a common superclass. It enables methods to behave differently based on the
object calling them, promoting flexibility and dynamic behavior.
2. Difference between compile-time (overloading) and runtime polymorphism (overriding)
Feature Compile-Time Polymorphism Runtime Polymorphism
Mechanism Method overloading or operator overloading Method overriding
Decision
At compile time At runtime
time
Functions with the same name but different Subclass redefining superclass
Example
parameters method
3. Method overloading vs method overriding
Method overloading:
Same method name but different parameter lists within the same class.
Method overriding:
A subclass provides its own implementation of a method defined in the parent class,
using the same signature.
4. Can constructors be overloaded? Can they be overridden?
Overloading: Yes, constructors can be overloaded. A class can have multiple
constructors with different parameters.
Overriding: No, constructors cannot be overridden because they are specific to the
class and are not inherited by subclasses.
5. What is operator overloading?
Operator overloading is a feature where operators like +, -, or * are given new functionality
for user-defined types (classes). It is supported in C++ but not in Java, where operators
cannot be redefined for objects.
✅ Abstraction
1. What is abstraction? How is it implemented?
Abstraction hides the complex implementation details and exposes only the essential
features to the user. It’s implemented using abstract classes and interfaces, where the class
defines the structure but leaves some methods without implementation, allowing subclasses
to provide the specific behavior.
2. Difference between abstract class and interface
Feature Abstract Class Interface
Inheritance Supports single inheritance Supports multiple inheritance
Can have both implemented Only abstract methods (before Java 8), with
Implementation
and abstract methods default methods allowed in later versions
Constructor Can have constructors Cannot have constructors
Access
Can define access modifiers All methods are public by default
modifiers
3. Why use interfaces instead of abstract classes?
Interfaces are used when you need multiple inheritance or when different classes share
behavior but not implementation. They enforce strict contracts without imposing code reuse
constraints and allow greater flexibility in designing loosely coupled systems.
4. Can abstract classes have constructors?
Yes, abstract classes can have constructors. These constructors are called when a subclass is
instantiated and are used to initialize common properties defined in the abstract class.
Constructors & Destructors
✅ Constructors & Destructors (Java Focused)
1. What is a constructor?
A constructor in Java is a special method that is called when an object is created. It is used to
initialize the object’s state or set default values to its fields. A constructor has the same name
as the class and does not have a return type, not even void.
For example:
class Person {
String name;
int age;
// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
2. Types of constructors (default, parameterized, copy constructor)
1. Default Constructor:
A constructor without parameters. If you don’t explicitly define one, Java provides a
no-argument default constructor.
2. class Car {
3. Car() {
4. System.out.println("Default constructor called");
5. }
6. }
7. Parameterized Constructor:
A constructor that accepts parameters to initialize object properties.
8. class Car {
9. String model;
10. Car(String model) {
11. this.model = model;
12. }
13. }
14. Copy Constructor:
Java doesn’t provide a built-in copy constructor like C++, but you can define one
manually to create a new object by copying values from an existing object.
15. class Car {
16. String model;
17. Car(Car car) {
18. this.model = car.model;
19. }
20. }
3. Difference between constructor and method
Feature Constructor Method
Purpose Initialize an object Perform an operation
Name Same as the class Any name
Return type No return type Has a return type or void
Automatically called when an object is Explicitly called after object
Invocation
created creation
Inheritance Not inherited by subclasses Inherited and can be overridden
4. What is a destructor? When is it called?
Java does not have destructors like C++ because it relies on garbage collection to reclaim
memory. However, Java provides a method called finalize() that is called by the garbage
collector before reclaiming the object’s memory, but it is not recommended to rely on it for
cleanup due to unpredictability in execution and performance concerns.
Example:
protected void finalize() throws Throwable {
System.out.println("Cleanup before object is garbage collected");
}
Use other cleanup methods like try-with-resources or explicitly close resources instead.
5. Difference between destructor in C++ and garbage collection in Java
Feature Destructor in C++ Garbage Collection in Java
Concept Explicit cleanup of resources Automatic memory management
Programmer or automatically JVM’s garbage collector at an unspecified
Called by
during object destruction time
Predictable – executes when
Predictability Unpredictable – depends on JVM's GC cycle
object is destroyed
Primarily for memory cleanup; use other
Usage Frees memory, closes files, etc.
mechanisms for resource management
Use finalize() (deprecated in later versions),
Syntax Defined using ~ClassName()
or manage resources explicitly
Advanced OOP Concepts
✅ Advanced OOP Concepts (Java Focused)
1. What is the static keyword? (static variables, methods, blocks)
The static keyword in Java is used to define class-level members that are shared among all
instances of the class, rather than being tied to a specific object.
Static variables:
These are shared across all objects of the class. Changes to the static variable affect
all instances.
class Counter {
static int count = 0;
}
Static methods:
These methods belong to the class, not the instance, and can be called without
creating an object.
class Utility {
static void printMessage() {
System.out.println("Hello from static method!");
}
}
Static blocks:
Used for initializing static variables when the class is loaded.
class Example {
static {
System.out.println("Static block executed.");
}
}
2. What are final/const keywords? Difference between them
final keyword:
Used to declare constants, prevent inheritance, or prevent method overriding in Java.
final int MAX_VALUE = 100; // Constant
Java doesn’t have a const keyword. In some languages like C++, const makes
variables immutable. In Java, final serves that purpose.
Difference:
const (Other languages
Feature final (Java)
like C++)
Available in Yes No
const (Other languages
Feature final (Java)
like C++)
Java
Used to declare constants, prevent Used to declare immutable
Purpose
inheritance/overriding values
Reassignment Not allowed after initialization Not allowed
3. What is this keyword?
this refers to the current object instance within a class. It’s used to resolve naming conflicts
between instance variables and method parameters, or to invoke other constructors.
Example:
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id; // Refers to the instance variable
this.name = name;
}
}
4. What is super keyword?
super is used to refer to the parent class members (variables, methods, constructors).
Access parent class methods:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Calls Animal’s sound method
System.out.println("Dog barks");
}
}
Call parent constructor:
class Animal {
Animal(String name) {
System.out.println("Animal: " + name);
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
}
5. What is object cloning?
Object cloning is creating a new object with the same state (field values) as an existing
object. In Java, it’s done using the clone() method provided by the Cloneable interface.
Example:
class Person implements Cloneable {
String name;
Person(String name) {
this.name = name;
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
6. What is shallow copy vs deep copy?
Shallow copy:
Copies object fields as they are, including references. If the object contains references
to other objects, both the original and the copy will refer to the same objects.
Deep copy:
Creates a completely independent copy by recursively copying all referenced objects.
Example:
class Address {
String city;
}
class Person implements Cloneable {
String name;
Address address;
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
Person deepClone() {
Address newAddress = new Address();
newAddress.city = this.address.city;
Person newPerson = new Person();
newPerson.name = this.name;
newPerson.address = newAddress;
return newPerson;
}
}
7. Difference between aggregation, composition, and association
Lifetime
Relationship Description
Dependency
A general relationship where objects are related but
Association None
independent
“Has-a” relationship where one object contains another but
Aggregation Partial
both can exist independently
Strong “part-of” relationship where the child object’s
Composition Full
lifecycle depends on the parent
Example:
Association → Teacher and Student
Aggregation → Library has Books (books can exist without the library)
Composition → House has Rooms (rooms can't exist without the house)
8. What is dependency injection in OOP?
Dependency Injection (DI) is a design pattern where an object’s dependencies are provided
from outside rather than being created inside the object. This helps in making the code
loosely coupled, easier to test, and maintain.
Example:
class Engine {
void start() {
System.out.println("Engine starting...");
}
}
class Car {
private Engine engine;
Car(Engine engine) {
this.engine = engine; // Dependency injected
}
void start() {
engine.start();
}
}
You can inject dependencies via constructors, setters, or interfaces.
Design & Principles
✅ Design & Principles (OOP)
1. What are design patterns? Examples (Singleton, Factory, Observer)
Design patterns are proven, reusable solutions to common software design problems. They
provide a standard approach to designing flexible, maintainable, and scalable software.
Examples:
Singleton: Ensures only one instance of a class exists and provides a global point of
access.
Factory: Provides an interface for creating objects without specifying the exact class.
Observer: Defines a one-to-many dependency so that when one object changes
state, all its dependents are notified automatically.
Design patterns are categorized into creational, structural, and behavioral patterns.
2. What is the Singleton class? How to implement it?
A Singleton class restricts the instantiation of a class to a single object and provides a global
point of access to that instance.
Implementation (thread-safe in Java):
class Singleton {
private static Singleton instance;
private Singleton() {} // Private constructor
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Other approaches include eager initialization, double-checked locking, and enum-based
singleton for simplicity and thread safety.
3. What are SOLID principles in OOP? Explain briefly
SOLID is a set of five principles that guide good object-oriented design:
1. S – Single Responsibility Principle (SRP):
A class should have only one reason to change. Each class should have a single
responsibility.
2. O – Open/Closed Principle (OCP):
Classes should be open for extension but closed for modification, allowing new
functionality without changing existing code.
3. L – Liskov Substitution Principle (LSP):
Subclasses should be replaceable with their base classes without altering the
correctness of the program.
4. I – Interface Segregation Principle (ISP):
No client should be forced to depend on methods it does not use. Prefer smaller,
specific interfaces over large, general-purpose interfaces.
5. D – Dependency Inversion Principle (DIP):
High-level modules should not depend on low-level modules. Both should depend on
abstractions (interfaces).
4. What is cohesion and coupling? Which one is desirable?
Cohesion:
Measures how closely the responsibilities of a single module/class are related. High
cohesion is desirable as it makes the code more understandable, maintainable, and
reusable.
Coupling:
Measures the degree of dependency between modules/classes. Low coupling (loose
coupling) is desirable to reduce interdependencies and make the system more flexible
and maintainable.
5. Difference between tight coupling and loose coupling
Feature Tight Coupling Loose Coupling
High – classes heavily depend on Low – classes depend on abstractions or
Dependency
each other interfaces
Low – changes in one class affect High – changes in one class have
Flexibility
others minimal impact
Maintainability Harder to maintain and test Easier to maintain and test
Directly instantiating a concrete Using dependency injection or
Example
class interfaces
Loose coupling promotes modular, scalable, and testable code.
6. What is object-oriented design vs object-oriented analysis?
Object-Oriented Analysis (OOA):
Focuses on what the system should do. It involves identifying objects, classes,
relationships, and responsibilities without considering implementation details. OOA
helps in modeling real-world problems.
Object-Oriented Design (OOD):
Focuses on how the system will do it. It translates the analysis into classes, methods,
and interactions that can be implemented in code, considering design patterns and
best practices.
Example:
OOA identifies “Customer” and “Order” as objects, while OOD decides how OrderManager
interacts with Customer and Order using design patterns.
Operator & Function Overloading
✅ Operator & Function Overloading
1. What is operator overloading? Which operators can be overloaded?
Operator overloading allows giving custom meaning to existing operators for user-defined
types (classes). It enables intuitive use of operators like +, -, *, ==, etc., on objects.
Example:
class Complex {
public:
int real, imag;
Complex(int r, int i) : real(r), imag(i) {}
Complex operator + (const Complex &c) {
return Complex(real + c.real, imag + c.imag);
}
};
Supported operators: +, -, *, /, %, ==, !=, <, >, <=, >=, [], (), ->, ++, --, etc.
Cannot be overloaded: :: (scope), .*, ., sizeof, typeid, sizeof..., #, ##.
2. Why is operator overloading not supported in Java?
Java does not allow operator overloading to avoid complexity and maintain code
readability.
Overloading operators can lead to ambiguous code and make maintenance difficult.
Java encourages method overloading instead for similar functionality.
3. Difference between function overloading and operator overloading
Feature Function Overloading Operator Overloading
Define multiple functions with the same Provide custom behavior for
Purpose
name but different parameters operators on objects
Same function name, different parameter
Syntax Use operator keyword in C++
list
Supported
C++, Java, Python Only C++
in
Example int add(int a, int b); float add(float a, float Complex operator+(Complex c);
Feature Function Overloading Operator Overloading
b);
Concept Polymorphism at compile-time Polymorphism at compile-time
4. Can we overload the main() method?
Yes, in C++ or Java, you can overload main() with different parameters, but the entry point
of the program must always have the standard signature:
public static void main(String[] args) { ... }
Other overloaded versions can exist but won’t be called by the JVM at program start. They
can be invoked manually from the main method.
Example:
public class Test {
public static void main(String[] args) {
main(10); // Calls overloaded main
}
public static void main(int x) {
System.out.println("Overloaded main: " + x);
}
}
Exception Handling
✅ Exception Handling
1. What is exception handling in OOP?
Exception handling is a mechanism to handle runtime errors in a controlled manner,
preventing program crashes. In OOP, exceptions are treated as objects that describe an
abnormal condition. Exception handling allows a program to:
Detect errors (exceptions) at runtime.
Separate normal code from error-handling code.
Recover gracefully or terminate the program safely.
Example in Java:
try {
int result = 10 / 0; // May throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
2. Difference between checked and unchecked exceptions (Java)
Feature Checked Exceptions Unchecked Exceptions
Compile-time Checked by compiler; must be
Not checked by compiler
checking handled
ArithmeticException,
Example IOException, SQLException
NullPointerException
Handling Must be caught or declared in
Optional to catch or declare
requirement method signature
Programming errors (e.g., null
Cause External factors (e.g., file missing)
reference)
3. Try-catch-finally – how does it work?
try block: Contains code that might throw an exception.
catch block: Handles the exception thrown in the try block. You can have multiple
catch blocks for different exception types.
finally block: Contains code that always executes, whether an exception occurs or
not, typically used for cleanup (e.g., closing files or resources).
Example:
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
} finally {
System.out.println("Finally block executed.");
}
4. Difference between throw, throws, and Throwable
Keyword Purpose
throw Used to explicitly throw an exception in a method body.
Declares exceptions that a method may throw, passing responsibility to the
throws
caller.
Superclass of all exceptions and errors in Java. Includes Exception and Error
Throwable
classes.
Example:
public void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
}
Real World OOP Scenarios
✅ Real-World OOP Scenarios
1. Real-life examples of OOP concepts
OOP Concept Real-Life Example
Using an ATM: Users interact with deposit, withdraw, and balance-check
Abstraction
operations without knowing the underlying implementation.
Bank account: The account balance is private, and only accessible via
Encapsulation
methods like deposit() and withdraw().
Vehicle hierarchy: A Car and Bike inherit from a common Vehicle class,
Inheritance
sharing attributes like speed and color.
Payment system: CreditCardPayment, DebitCardPayment, UPIPayment
Polymorphism classes implement a common Payment interface. The system can process
payments without knowing the exact type.
2. Designing a Library Management System (LMS) or Banking System using OOP
Example: Library Management System
Classes: Book, Member, Librarian, Loan, Catalog
Abstraction: Provide high-level operations like borrowBook(), returnBook(),
searchBook() without exposing database queries.
Encapsulation: Keep book availability and member fines private; access them
through getters/setters.
Inheritance: Student and Faculty classes inherit from a Member base class, sharing
common attributes and methods.
Polymorphism: Overloaded searchBook() methods for searching by title, author, or
ISBN.
Composition/Aggregation: Loan class has Book and Member objects to track
borrowing relationships.
Banking System Example:
Classes: Account, SavingsAccount, CheckingAccount, Transaction, Customer.
Use abstraction for operations like deposit() and withdraw().
Inheritance for account types (SavingsAccount extends Account).
Polymorphism for transaction types: DepositTransaction and WithdrawalTransaction
implementing a common interface Transaction.
3. Why do we prefer OOP over procedural programming in large projects?
Modularity: Classes encapsulate data and methods, making code easier to manage.
Reusability: Inheritance and polymorphism reduce code duplication.
Maintainability: Encapsulated and modular code is easier to debug and update.
Scalability: Object-oriented designs allow seamless addition of new features with
minimal changes.
Real-world modeling: OOP aligns naturally with real-world entities and relationships,
improving understanding and design clarity.
4. Disadvantages of OOP
Memory overhead: Objects consume more memory due to metadata and references.
Complexity: Designing OOP systems can be more complex and time-consuming
initially.
Performance: Method calls, especially virtual method dispatch, can be slower
compared to procedural code.
Over-engineering risk: Small projects may not benefit from full OOP, leading to
unnecessary abstraction layers.
Steep learning curve: Requires understanding of classes, inheritance, polymorphism,
and design patterns.