OOPs interview questions: object-oriented programming explained with code

OOPs interview questions, also searched as object oriented programming interview questions, test whether you can explain encapsulation, abstraction, inheritance and polymorphism with real code, choose between an abstract class, an interface and composition, and design a small set of classes that is easy to change. Expect definitions first, then "what does this code print" questions on overriding and overloading, then SOLID and a low-level design task such as a parking lot. Showing the same idea in more than one language, such as Java, Python or C#, signals that you understand the concept and not only one syntax.

By Published 9 min read

How OOP questions are asked

Object-oriented programming is tested in campus and fresher interviews as a theory round, in Java, C# and Python developer screens as code-reading questions, and in experienced loops as a low-level design (LLD) or machine-coding round where you model a system in classes. The language matters less than people think: interviewers accept any mainstream OOP language, but they notice when an answer only repeats a textbook line. Tie every definition to a small example and to the problem it solves.

The four pillars, with code

Core concepts asked in almost every OOPs round
QuestionWhat it testsWhat a strong answer shows
What is encapsulation?State protectionKeeping an object's data private and changing it only through methods that keep it valid. A bank account exposes deposit and withdraw, not a writable balance field.
What is abstraction?Hiding detailExposing what an object does and hiding how. Callers use PaymentGateway.charge() without knowing which provider or HTTP calls sit behind it.
What is inheritance?Reuse and hierarchyA class takes on the members of a parent and can extend or override them. It models an "is a" relationship and couples the child tightly to the parent.
What is polymorphism?SubstitutionOne interface, many implementations: code written against Shape works with any shape, and the right area() runs for each object.
Class versus object?BasicsA class is the definition (fields and methods); an object is one instance of it in memory with its own state.
Abstraction versus encapsulation?PrecisionAbstraction decides what to show to callers; encapsulation is the mechanism that hides and guards the rest. They work together but are not the same idea.
Core concepts asked in almost every OOPs round. Scroll sideways on a small screen.
import java.util.List;

abstract class Shape {
    abstract double area();

    String describe() {                       // shared behavior, inherited by every shape
        return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
    }
}

class Circle extends Shape {
    private final double radius;              // encapsulated, set once
    Circle(double radius) { this.radius = radius; }
    @Override double area() { return Math.PI * radius * radius; }
}

class Rectangle extends Shape {
    private final double width, height;
    Rectangle(double width, double height) { this.width = width; this.height = height; }
    @Override double area() { return width * height; }
}

public class Main {
    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1), new Rectangle(2, 3));
        for (Shape s : shapes) System.out.println(s.describe());   // dispatch on the real type
    }
}
Java: an abstract class, encapsulated fields and run-time polymorphism. Prints "Circle with area 3.14" then "Rectangle with area 6.00".
from abc import ABC, abstractmethod
import math


class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...

    def describe(self) -> str:
        return f"{type(self).__name__} with area {self.area():.2f}"


class Circle(Shape):
    def __init__(self, radius: float):
        self._radius = radius  # leading underscore: internal by convention

    def area(self) -> float:
        return math.pi * self._radius ** 2


class Rectangle(Shape):
    def __init__(self, width: float, height: float):
        self._width, self._height = width, height

    def area(self) -> float:
        return self._width * self._height


for shape in [Circle(1), Rectangle(2, 3)]:
    print(shape.describe())
Python: the same design with the abc module. Instantiating Shape directly raises TypeError.
using System;
using System.Collections.Generic;

abstract class Shape
{
    public abstract double Area();
    public virtual string Describe() => GetType().Name + " with area " + Area().ToString("F2");
}

sealed class Circle : Shape
{
    private readonly double _radius;
    public Circle(double radius) => _radius = radius;
    public override double Area() => Math.PI * _radius * _radius;
}

sealed class Rectangle : Shape
{
    public double Width { get; }
    public double Height { get; }
    public Rectangle(double width, double height) { Width = width; Height = height; }
    public override double Area() => Width * Height;
}

class Program
{
    static void Main()
    {
        var shapes = new List<Shape> { new Circle(1), new Rectangle(2, 3) };
        foreach (var s in shapes) Console.WriteLine(s.Describe());
    }
}
C#: methods must be marked virtual or abstract to be overridden, and sealed stops further inheritance.

Overloading, overriding and binding

  • Overloading versus overriding? Overloading is several methods with the same name and different parameter lists in one class, chosen by the compiler from the argument types (compile-time polymorphism). Overriding replaces a parent's method in a subclass, chosen at run time from the actual object (run-time polymorphism).
  • Does Python support overloading? Not by signature: a second def with the same name replaces the first. You use default arguments, *args, or functools.singledispatch instead.
  • Are methods virtual by default? In Java, yes: every non-static, non-private, non-final instance method can be overridden. In C#, no: the parent must say virtual and the child override. In Python every method lookup is dynamic.
  • Can you override a static method? No. In Java a static method with the same signature in a subclass hides the parent's; which one runs depends on the declared type, not the object.
  • What does C#'s `new` modifier on a method do? It hides the base method instead of overriding it. Called through a base-class variable, the base version runs, which surprises people in output questions.
  • What are `this` and `super` (or `base`) for? this refers to the current object and can call another constructor of the same class. super in Java and Python, or base in C#, reaches the parent's constructor or its version of an overridden method.
  • Why should a constructor not call an overridable method? The subclass override runs before the subclass's own fields are initialized, so it can see default values and fail in confusing ways.
using System;

Base b = new Derived();
Console.WriteLine(b.Who());   // Derived
Console.WriteLine(b.Name());  // Base

class Base
{
    public virtual string Who() => "Base";
    public string Name() => "Base";
}

class Derived : Base
{
    public override string Who() => "Derived";
    public new string Name() => "Derived";
}
A favorite C# output question: override is chosen by the object, new is chosen by the variable's declared type.

Abstract classes, interfaces and composition

Intermediate questions on structuring code
QuestionWhat it testsWhat a strong answer shows
Abstract class or interface?Design choiceAn abstract class shares state and code among closely related classes. An interface is a contract any class can sign. Since Java 8 and C# 8, interfaces can carry default methods, but they still cannot hold instance state.
Why does Java not allow multiple class inheritance?Diamond problemTwo parents could supply conflicting state and methods. Java and C# allow many interfaces instead; if two default methods clash, the class must override and choose.
How does Python handle multiple inheritance?MROIt linearizes the class hierarchy with the C3 algorithm into a method resolution order, and super() follows that order rather than calling the literal parent.
What does "favor composition over inheritance" mean?CouplingBuild behavior by holding other objects and delegating to them. You can swap parts at run time and avoid fragile deep hierarchies.
What is an "is a" versus "has a" relationship?ModelingA car is a vehicle (inheritance may fit). A car has an engine (composition). Getting this wrong is behind many awkward hierarchies.
Association, aggregation and composition?UML vocabularyAssociation is any link between objects. Aggregation is a whole that holds parts which can exist alone (a team and its players). Composition is ownership where parts die with the whole (an order and its line items).
What is duck typing?Dynamic languagesIn Python an object fits wherever it has the methods being called; no declared interface is needed. typing.Protocol lets type checkers verify that structurally.
Intermediate questions on structuring code. Scroll sideways on a small screen.
class A:
    def hello(self):
        return "A"

class B(A):
    def hello(self):
        return "B then " + super().hello()

class C(A):
    def hello(self):
        return "C then " + super().hello()

class D(B, C):
    pass

print(D().hello())                       # B then C then A
print([k.__name__ for k in D.__mro__])   # ['D', 'B', 'C', 'A', 'object']
Python's method resolution order on a diamond: super() walks the MRO, so each class runs once.

Object identity, equality and lifecycle

  • What is the equals and hashCode contract in Java? Objects that are equal must return the same hash code. Override one without the other and a HashSet can hold two "equal" objects or fail to find one. Java records generate both for you.
  • `==` versus `equals` (or `is` versus `==` in Python)? == on references (and is in Python) compares identity; equals (and == in Python, via __eq__) compares value as the class defines it.
  • Why make objects immutable? They are safe to share between threads, safe as map keys, and easier to reason about. Use final or readonly fields, no setters, and defensive copies of mutable inputs.
  • Shallow copy versus deep copy? A shallow copy duplicates the outer object but shares nested objects; a deep copy duplicates everything reachable. Mutating a nested list after a shallow copy changes both.
  • How are objects cleaned up? Java and C# use garbage collection, so release files and connections explicitly: try-with-resources in Java, using with IDisposable in C#, with and context managers in Python. Finalizers are a last resort, not a cleanup plan.
  • What are access modifiers? Java has private, package-private (the default), protected and public. C# adds internal, protected internal and private protected. Python has no enforcement: one underscore means internal by convention, two trigger name mangling.
import java.util.Objects;

final class Money {
    private final long cents;
    private final String currency;

    Money(long cents, String currency) {
        this.cents = cents;
        this.currency = Objects.requireNonNull(currency);
    }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Money)) return false;
        Money other = (Money) o;
        return cents == other.cents && currency.equals(other.currency);
    }

    @Override public int hashCode() { return Objects.hash(cents, currency); }
}

// equivalent: record Money(long cents, String currency) {}
Java: a value object with equals and hashCode kept consistent. A record would generate the same methods.

SOLID, patterns and low-level design

Questions for experienced developers
QuestionWhat it testsWhat a strong answer shows
Explain SOLID with an example of each.PrinciplesSingle responsibility (one reason to change), open/closed (extend without editing), Liskov substitution (subtypes keep the parent's promises), interface segregation (small interfaces), dependency inversion (depend on abstractions, inject them).
Why is a Square subclass of Rectangle a Liskov problem?LSPCode that sets width and height independently breaks when a square forces them equal. The subtype cannot keep the parent's contract, so it should not inherit.
What is dependency injection?TestabilityAn object receives its collaborators (through the constructor, usually) instead of creating them, so tests can pass fakes and wiring lives in one place.
Strategy pattern: when would you use it?PatternsWhen an algorithm varies (pricing rules, compression), put each variant behind one interface and choose at run time, instead of a growing if-else chain.
Factory versus builder?CreationA factory decides which class to create; a builder assembles one complex object step by step with readable optional parts.
Observer pattern and its risk?EventsSubscribers are notified when a subject changes. Forgetting to unsubscribe keeps objects alive and causes leaks.
Why is Singleton often criticized?Global stateIt hides a dependency, makes tests share state and complicates concurrency. Prefer one instance managed by the composition root or the DI container.
Decorator versus inheritance?ExtensionA decorator wraps an object with the same interface to add behavior (logging, caching) at run time, and wrappers can be stacked; subclassing fixes the combination at compile time.
Cohesion and coupling?QualityHigh cohesion: a class's members belong together. Low coupling: classes know little about each other. Good OOP design aims for both.
Design the classes for a parking lot.LLD roundClarify requirements first, then entities (ParkingLot, Level, Spot types, Vehicle types, Ticket, Payment), a strategy for spot allocation and pricing, and where concurrency matters when two cars take the same spot.
Questions for experienced developers. Scroll sideways on a small screen.

Fictional example

Answering "Design a notification sender that supports email, SMS and push"
Interviewer
We send notifications by email and SMS today and want push next quarter. Show me the classes.
Candidate
I would define a Channel interface with one method, send(Recipient, Message), and one class per channel: EmailChannel, SmsChannel, and later PushChannel. A NotificationService receives a map of channels through its constructor and picks one from the user's preference, so adding push means one new class and one line of wiring, without editing the service. That is open/closed and dependency inversion in practice. Retries and logging are cross-cutting, so I would add them as a decorator that wraps any channel rather than putting them in each class. I would not use inheritance between channels, because they share a contract, not code. For tests I pass a fake channel that records messages. If a channel needs rate limits, that lives inside it, not in the service.

OOPs interview practice plan

  1. Write the pillars from memoryOne definition and one ten-line example each, in your main language and then in a second one. Translating shows you which ideas are concepts and which are syntax.
  2. Drill output questionsWrite small programs that mix overloading, overriding, static methods and hiding, predict the output, then run them.
  3. Refactor a hierarchyTake a deep inheritance tree from an old project or a kata and rebuild it with composition and interfaces. Note what got easier to test.
  4. Practice two LLD problemsA parking lot and a library or elevator system: requirements, classes, relationships, one pattern you would use and why, within 45 minutes.
  5. Explain SOLID with your own codeFor each principle, find a place in your own work where you followed it or broke it. Interviewers remember real examples.

OOP sits next to the other fundamentals interviewers check: data structures interview questions covers the collections your classes will hold, REST API interview questions covers the contracts objects end up behind, and software engineer interview questions shows how these rounds fit a full loop.

Output-prediction questions are easy to get almost right. Natively, an AI interview assistant for Mac and Windows, can read a screenshot of a code snippet during practice and walk through which method actually runs and why, and it transcribes your mock LLD discussion so you can see whether you clarified requirements before drawing classes. With Pro or the free trial it can also use your résumé and the job description you add. Transcripts and notes are kept for you to look back on.

Questions people ask

What are the most common OOPs interview questions?

The four pillars with examples, class versus object, overloading versus overriding, abstract class versus interface, composition versus inheritance, the diamond problem, SOLID, and a small class design such as a parking lot.

What are the four pillars of object-oriented programming?

Encapsulation (guarding an object's state behind methods), abstraction (exposing what an object does, not how), inheritance (reusing and extending a parent class) and polymorphism (one interface, many implementations).

What is the difference between overloading and overriding?

Overloading means methods with the same name but different parameters, chosen by the compiler. Overriding means a subclass replaces a parent method, and the version that runs is chosen at run time from the actual object.

Which language should I use for an OOP interview?

The one you know best among Java, C#, Python or C++, unless the job names one. Interviewers judge the concepts, but they expect correct syntax and idioms in the language you pick.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP