Software Engineer | 49 questions | 2026
OOP Interview Questions and Answers
OOP interview questions for freshers 24
Q1FresherMost askedAnswerHideWhat are the four pillars of OOP?
The four pillars are encapsulation, abstraction, inheritance and polymorphism.
- Encapsulation: keep data and the methods that work on it in one class. Hide the internal state behind a controlled interface.
- Abstraction: expose only what a caller needs (the "what") and hide the implementation (the "how").
- Inheritance: a child class reuses and extends the fields and behaviour of a parent class.
- Polymorphism: one interface, many forms. The same call behaves differently depending on the object (overloading at compile time, overriding at run time).
class Shape:
def area(self): raise NotImplementedError
class Circle(Shape):
def __init__(self, r): self._r = r # encapsulated state
def area(self): return 3.14159 * self._r ** 2
for s in [Circle(1), Circle(2)]:
print(s.area()) # polymorphic call
What they are checking: Whether you know the four terms and can attach a one-line meaning and example to each
Q2FresherMost askedAnswerHideWhat is the difference between a class and an object?
A class is a blueprint (a type definition with fields and methods). An object is a concrete instance of that class that exists in memory with its own state.
- Class: defined once, no memory for instance data until used. Example:
Car. - Object: created with
new(Java) or by calling the class (Python). Many objects can come from one class, each with its own field values.
class Car { String color; void drive() { System.out.println(color + " car moves"); } }
Car a = new Car(); a.color = "red";
Car b = new Car(); b.color = "blue"; // two objects, one class
class Car:
def __init__(self, color): self.color = color
a, b = Car("red"), Car("blue")
What they are checking: Basic clarity on type versus instance
Q3FresherMost askedAnswerHideWhat is the difference between an abstract class and an interface?
Both define a contract, but they differ in what they can hold and how they are used.
| Abstract class | Interface | |
|---|---|---|
| State | Can have instance fields | Only constants (public static final) |
| Methods | Abstract and concrete, any access modifier | Abstract, default, static, private (Java 8+/9+) |
| Constructor | Yes | No |
| Inheritance | A class extends only one | A class implements many |
| Use | "is-a" with shared code and state | A capability or role (Comparable, Runnable) |
Pick an abstract class when subclasses share fields and a partial implementation. Pick an interface when unrelated classes should offer the same behaviour or you need multiple inheritance of type.
In Python, use abc.ABC for both ideas: a class with only abstract methods acts like an interface.
What they are checking: Whether you can choose between them and not just list syntax
Q4FresherMost askedAnswerHideWhat is the difference between method overloading and method overriding?
Overloading: same method name in the same class with different parameter lists. It is resolved at compile time (static polymorphism). Overriding: a subclass provides its own body for a method with the same signature as in its parent. It is resolved at run time (dynamic polymorphism).
| Overloading | Overriding | |
|---|---|---|
| Where | Same class (or subclass) | Parent and child class |
| Signature | Must differ | Must match |
| Return type | Can differ | Same or covariant |
| Binding | Compile time | Run time |
class A { void show(int x) {} void show(String s) {} } // overloading
class B { void run() { System.out.println("B"); } }
class C extends B { @Override void run() { System.out.println("C"); } }
Python has no true overloading (the last def wins); use default arguments or functools.singledispatch.
What they are checking: Core polymorphism knowledge and awareness of compile time versus run time
Q5FresherMost askedAnswerHideWhat is encapsulation? Give an example.
Encapsulation means keeping data private inside a class and giving access only through methods. So the class controls how its state changes and can protect its rules (invariants).
public class Account {
private double balance; // hidden
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amt;
}
public double getBalance() { return balance; }
}
Benefits: validation in one place, freedom to change internals without breaking callers, and fewer bugs from outside code touching fields directly. In Python, a single underscore (_balance) is a convention for "internal" and @property gives controlled access.
What they are checking: Whether you link encapsulation to protecting rules that must always be true, not just private fields
Q6FresherMost askedAnswerHideWhat is polymorphism? Explain compile-time and run-time polymorphism.
Polymorphism means one name or interface, many behaviours.
- Compile-time (static): method overloading and operator overloading. The compiler picks the method from the argument types.
- Run-time (dynamic): method overriding. A parent reference holding a child object calls the child's version, chosen at run time.
abstract class Shape { abstract double area(); }
class Square extends Shape { double s = 2; double area() { return s * s; } }
class Circle extends Shape { double r = 1; double area() { return Math.PI * r * r; } }
Shape sh = new Circle();
System.out.println(sh.area()); // Circle's area, decided at run time
The payoff: callers depend on the abstraction (Shape) and new subclasses plug in without changing them.
What they are checking: Whether you can give a real example of dynamic dispatch
Q7FresherMost askedAnswerHideWhat are the SOLID principles?
SOLID is five design principles for maintainable object-oriented code.
- S, Single Responsibility: a class should have one reason to change.
- O, Open/Closed: open for extension, closed for modification. Add behaviour by adding code, not editing tested code.
- L, Liskov Substitution: a subclass must be usable wherever its parent is expected without breaking correctness.
- I, Interface Segregation: prefer several small interfaces to one fat interface.
- D, Dependency Inversion: depend on abstractions, not concrete classes. High-level code should not import low-level details.
Quick example: an OrderService that builds PDF invoices, sends email and writes to the database breaks S. Split it, and inject an InvoiceSender interface (D) so you can add SMS later without editing the service (O).
What they are checking: Whether you can state all five and tie them to practice
Q8FresherMost askedAnswerHideWhat is the contract between equals() and hashCode() in Java?
Rules:
- If
a.equals(b)is true, thena.hashCode() == b.hashCode(). - If hash codes are equal, the objects may or may not be equal (collisions).
equalsmust be reflexive, symmetric, transitive, consistent and return false for null.
If you override equals but not hashCode, equal objects can land in different buckets, so HashMap/HashSet fail to find them.
public final class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}
@Override public int hashCode() { return java.util.Objects.hash(x, y); }
}
Do not use mutable fields in hashCode for keys: mutating a key after inserting it loses the entry. Records generate both methods for you.
What they are checking: A very common follow-up; checks hashing fundamentals
Q9FresherMost askedAnswerHideWhat is inheritance, and what are its types?
Inheritance lets a class (child) get the fields and methods of another class (parent). Common code is written once, and the child adds or changes behaviour.
Types:
- Single: B extends A.
- Multilevel: C extends B extends A.
- Hierarchical: B and C both extend A.
- Multiple: a class has more than one parent. Java allows it only through interfaces; Python and C++ allow it for classes.
- Hybrid: a mix of the above.
class Animal { void eat() { System.out.println("eats"); } }
class Dog extends Animal { void bark() { System.out.println("barks"); } }
Use it for real "is-a" relationships only. For code reuse alone, prefer composition.
What they are checking: Vocabulary plus judgement about when to use it
Q10FresherMost askedAnswerHideWhat is abstraction, and how is it different from encapsulation?
Abstraction hides complexity by showing only essential behaviour (design level: what a thing does). Encapsulation hides data by limiting access to a class's internals (implementation level: how state is protected).
- Abstraction is achieved with abstract classes and interfaces. Example: you call
list.sort()without knowing the algorithm. - Encapsulation is achieved with access modifiers and getters/setters. Example: a private
balancewith a validateddeposit.
They work together: an interface gives the abstract view, and encapsulation keeps the concrete class's state safe behind it.
What they are checking: The common confusion between these two pillars
Q11FresherMost askedFree with sign-inAnswerHideWhat is the Singleton pattern, and how do you implement it thread-safely?
Singleton guarantees one instance of a class and a global access point. Typical uses: configuration, logger, connection pool.
Thread-safe Java options:
Q12FresherMost askedFree with sign-inAnswerHideWhat is the Factory pattern, and when would you use it?
A factory creates objects without the caller naming the concrete class. The caller asks for a type and gets something that implements an interface.
Q13FresherMost askedFree with sign-inAnswerHideWhat is a constructor? How is it different from a method?
A constructor is a special block that runs when an object is created and initialises its state.
Q14FresherMost askedFree with sign-inAnswerHideWhat are the access modifiers in Java and what does each allow?
Java has four levels of visibility:
Q15FresherMost askedFree with sign-inAnswerHideExplain the Single Responsibility Principle with an example.
A class should have one reason to change, meaning it serves one actor or concern.
Example of breaking it: an Employee class that calculates pay, saves itself to the database and prints reports. A change in tax rules, in the schema or in report layout all force edits to the same class.
Q16FresherMost askedFree with sign-inAnswerHideExplain the Open/Closed Principle with an example.
Software entities should be open for extension but closed for modification: add new behaviour without editing code that already works.
Example of breaking it: a discount function with an if/elif per customer type. Every new type edits it.
Q17FresherMost askedFree with sign-inAnswerHideHow does OOP in Python differ from Java?
- Typing: Python is dynamically typed and relies on duck typing (if it has
quack(), it works). Java is statically typed and needs types and interfaces written out. - Access control: Python has none enforced;
_xis a convention and__xis name-mangled. Java hasprivate,protected,public. -...
Q18FresherMost askedFree with sign-inAnswerHideHow do you create an abstract class in Python?
Use the abc module: inherit from ABC and mark methods with @abstractmethod. A class with unimplemented abstract methods cannot be instantiated.
Q19FresherMost askedFree with sign-inAnswerHideWhat is the difference between instance, class and static methods in Python?
| Type | First argument | Access to | Typical use |
|---|---|---|---|
| Instance method | self | Object and class | Normal behaviour |
@classmethod | cls | Class only | Alternative constructors, class-level state |
@staticmethod | none | Neither | Utility tied to the class by topic |
class User:...
Q20FresherMost askedFree with sign-inAnswerHideWhat do the this and super keywords do?
this refers to the current object. super refers to the parent class part of it.
Q21FresherMost askedFree with sign-inAnswerHideWhat is the difference between static and instance members?
Static members belong to the class and are shared by all objects. Instance members belong to each object.
- Static: one copy, accessed as
ClassName.member, loaded with the class. A static method cannot usethisor instance fields directly. - Instance: each object has its own copy.
Q22FresherMost askedFree with sign-inAnswerHideWhat are default and static methods in interfaces?
Since Java 8, an interface can contain method bodies.
Q23FresherMost askedFree with sign-inAnswerHideCan you override a static or private method?
No. Static methods belong to the class. So a subclass method with the same signature only hides the parent's method (method hiding). The call is resolved at compile time by the reference type. Private methods are not visible to subclasses. So a child method with the same name is a new method, not an override.
Q24FresherMost askedFree with sign-inAnswerHideWhat is the difference between tight coupling and loose coupling, and what is cohesion?
Coupling is how much one class depends on another. Cohesion is how closely the parts of a single class belong together.
OOP interview questions for experienced 16
Q25ExperiencedMost askedFree with sign-inAnswerHideComposition vs inheritance: which do you prefer and why?
Prefer composition ("has-a") over inheritance ("is-a") unless there is a genuine subtype relationship.
Q26ExperiencedMost askedFree with sign-inAnswerHideWhat is the Observer pattern? Give a real-world use.
Observer defines a one-to-many dependency: when a subject changes state, all its registered observers are notified automatically, with no tight coupling between them.
Q27ExperiencedMost askedFree with sign-inAnswerHideWhat is the Liskov Substitution Principle? Give an example of breaking it.
If S is a subtype of T, you can use objects of S in place of objects of T without breaking the program. A subclass must honour the parent's contract: same preconditions or weaker, same postconditions or stronger, no new exceptions.
Q28ExperiencedMost askedFree with sign-inAnswerHideWhat is the difference between Dependency Inversion and Dependency Injection?
Dependency Inversion (the D in SOLID) is a design principle: high-level modules should depend on abstractions, not on concrete low-level classes.
Dependency Injection (DI) means giving a class the objects it needs from outside (constructor, setter or framework). The class does not create them inside with new.
Q29ExperiencedMost askedFree with sign-inAnswerHideHow do you create an immutable class in Java, and why would you?
Immutable objects cannot change after they are built. So they are thread-safe by default, safe as map keys and easy to understand (String, Integer, LocalDate).
Q30ExperiencedMost askedFree with sign-inAnswerHideWhen would you use an abstract class and when an interface in a real project?
Use an interface to describe a capability that unrelated classes can offer and that callers depend on: PaymentGateway, Repository, Comparable. It keeps coupling low and makes mocks easy.
Q31ExperiencedMost askedFree with sign-inAnswerHideWhat is the diamond problem, and how do Java and Python handle it?
The diamond problem appears with multiple inheritance: D inherits from B and C, which both inherit from A. If B and C override a method differently, which version does D get?
Q32ExperiencedMost askedFree with sign-inAnswerHideWhat is the Interface Segregation Principle?
Clients should not be forced to depend on methods they do not use. Prefer several small, focused interfaces over one large one.
Example of breaking it:
Q33ExperiencedMost askedFree with sign-inAnswerHideHow does run-time polymorphism work internally?
It uses dynamic dispatch. In Java each class has a method table (vtable). Every object carries a reference to its class. For an overridden method call, the JVM looks up the method in the real object's class at run time, not in the declared reference type.
Q34ExperiencedMost askedFree with sign-inAnswerHideHow does Method Resolution Order (MRO) work in Python, and what does super() do?
MRO is the order Python searches classes for an attribute. It uses C3 linearisation, which keeps each class before its parents and preserves the order of bases as written. Class.__mro__ or Class.mro() shows it.
Q35ExperiencedMost askedFree with sign-inAnswerHideWhat are __init__, __new__ and other dunder methods in Python?
Dunder (double underscore) methods let your class plug into Python's syntax and built-ins.
Q36ExperiencedMost askedFree with sign-inAnswerHideWhat is the difference between shallow copy and deep copy of an object?
A shallow copy creates a new outer object but the nested objects are shared with the original. A deep copy recursively copies everything, so the two are independent.
Q37ExperiencedMost askedFree with sign-inAnswerHideWhat is the Strategy pattern and how does it relate to the Open/Closed Principle?
Strategy defines a family of interchangeable algorithms behind one interface and lets the caller pick one at run time. The context holds a reference to the interface and delegates.
Q38ExperiencedMost askedFree with sign-inAnswerHideWhat is the Decorator pattern, and how is it different from a Python decorator?
The Decorator design pattern wraps an object with another that has the same interface to add behaviour dynamically, without subclassing. Example: BufferedReader(new FileReader(...)).
Q39ExperiencedMost askedFree with sign-inAnswerHideWhat is the Builder pattern and when is it useful?
Builder constructs a complex object step by step and produces it at the end. It is useful when a class has many optional parameters, or construction must be validated as a whole.
Q40ExperiencedMost askedFree with sign-inAnswerHideWhat are records and sealed classes in modern Java, and how do they help OOP design?
Record (Java 16): a compact immutable data carrier. The compiler generates the constructor, accessors, equals, hashCode and toString.
Scenario based OOP interview questions 9
Q41ExperiencedMost askedScenarioFree with sign-inAnswerHideHow would you replace a long if/else or switch on object type with polymorphism?
Move each branch's behaviour into a class that implements a shared interface, and let dynamic dispatch pick the branch.
Before:
Q42ExperiencedMost askedScenarioFree with sign-inAnswerHideDesign the classes for a parking lot system. How do you approach it?
Clarify requirements first: vehicle types, number of levels, pricing, entry and exit, payment, capacity display.
Q43ExperiencedMost askedScenarioFree with sign-inAnswerHideYou must add a new payment method without modifying existing checkout code. How would you design it?
Apply Open/Closed with a Strategy interface and a registry.
Q44ExperiencedMost askedScenarioFree with sign-inAnswerHideDesign a notification system where users choose email, SMS or push, and new channels will be added later.
Use Strategy for channels. Use a factory or registry to look them up. Use Observer if one event goes to many subscribers.
Q45ExperiencedMost askedScenarioFree with sign-inAnswerHideA subclass overrides a method and throws an exception for operations it cannot support, breaking callers. What do you do?
This breaks the Liskov Substitution rule: the child cannot honestly stand in for the parent.
Q46ExperiencedMost askedScenarioFree with sign-inAnswerHideYour Singleton makes unit tests hard because state leaks between tests. How do you fix it?
The problem is hidden global state plus hard-wired access.
Q47ExperiencedMost askedScenarioFree with sign-inAnswerHideA class hierarchy has become five levels deep and every change breaks subclasses. How do you untangle it?
This is the fragile base class problem. Approach:
Q48ExperiencedMost askedScenarioFree with sign-inAnswerHideA constructor now takes eight parameters and many are optional. How do you clean it up?
This is the telescoping constructor smell. Options:
Q49ExperiencedMost askedScenarioFree with sign-inAnswerHideYou find a God class with 3000 lines that everything depends on. How do you break it down safely?
Plan:
- Add tests around the public behaviour (characterisation tests), even rough ones.
- Group methods and fields by the data they touch. Clusters that use separate fields are separate responsibilities.
- Extract classes one at a time (Extract Class refactoring). Move a cluster and its fields to a new...