Oop Questions

Software Engineer | 49 questions | 2026

OOP Interview Questions and Answers

Four pillars, SOLID, interfaces, design patterns. Tap a question to open the model answer, most asked first.

OOP interview questions for freshers 24

Q1FresherMost asked
Answer

What 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 asked
Answer

What 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 asked
Answer

What 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 classInterface
StateCan have instance fieldsOnly constants (public static final)
MethodsAbstract and concrete, any access modifierAbstract, default, static, private (Java 8+/9+)
ConstructorYesNo
InheritanceA class extends only oneA class implements many
Use"is-a" with shared code and stateA 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 asked
Answer

What 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).

OverloadingOverriding
WhereSame class (or subclass)Parent and child class
SignatureMust differMust match
Return typeCan differSame or covariant
BindingCompile timeRun 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 asked
Answer

What 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 asked
Answer

What 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 asked
Answer

What 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 asked
Answer

What is the contract between equals() and hashCode() in Java?

Rules:

  1. If a.equals(b) is true, then a.hashCode() == b.hashCode().
  2. If hash codes are equal, the objects may or may not be equal (collisions).
  3. equals must 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 asked
Answer

What 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 asked
Answer

What 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 balance with a validated deposit.

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-in
Answer

What 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-in
Answer

What 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-in
Answer

What 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-in
Answer

What are the access modifiers in Java and what does each allow?

Java has four levels of visibility:

Q15FresherMost askedFree with sign-in
Answer

Explain 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-in
Answer

Explain 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-in
Answer

How 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; _x is a convention and __x is name-mangled. Java has private, protected, public. -...
Q18FresherMost askedFree with sign-in
Answer

How 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-in
Answer

What is the difference between instance, class and static methods in Python?

TypeFirst argumentAccess toTypical use
Instance methodselfObject and classNormal behaviour
@classmethodclsClass onlyAlternative constructors, class-level state
@staticmethodnoneNeitherUtility tied to the class by topic
class User:...
Q20FresherMost askedFree with sign-in
Answer

What 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-in
Answer

What 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 use this or instance fields directly.
  • Instance: each object has its own copy.
Q22FresherMost askedFree with sign-in
Answer

What are default and static methods in interfaces?

Since Java 8, an interface can contain method bodies.

Q23FresherMost askedFree with sign-in
Answer

Can 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-in
Answer

What 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-in
Answer

Composition 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-in
Answer

What 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-in
Answer

What 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-in
Answer

What 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-in
Answer

How 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-in
Answer

When 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-in
Answer

What 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-in
Answer

What 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-in
Answer

How 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-in
Answer

How 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-in
Answer

What 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-in
Answer

What 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-in
Answer

What 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-in
Answer

What 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-in
Answer

What 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-in
Answer

What 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-in
Answer

How 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-in
Answer

Design 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-in
Answer

You 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-in
Answer

Design 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-in
Answer

A 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-in
Answer

Your 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-in
Answer

A 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-in
Answer

A 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-in
Answer

You find a God class with 3000 lines that everything depends on. How do you break it down safely?

Plan:

  1. Add tests around the public behaviour (characterisation tests), even rough ones.
  2. Group methods and fields by the data they touch. Clusters that use separate fields are separate responsibilities.
  3. Extract classes one at a time (Extract Class refactoring). Move a cluster and its fields to a new...
Test yourself on OOPQuick MCQs, right or wrong shown instantlyStart

More Software Engineer interview questions