OOP is asked in almost every software placement interview in India — service companies, product companies and startups alike — and it is a standard theory paper in university exams. Interviewers rarely want textbook definitions only. They want to see that you understand why a concept exists, can give a real example, and can predict what a piece of code will print.
This chapter collects the most frequently asked OOP questions, grouped by topic, with short, precise answers. Each group points back to the chapter where the idea is explained in detail. Try to answer each question aloud before opening the answer. The last section contains "predict the output" questions; all of them were compiled and run (Java 17, g++ with -std=c++23, Python 3.14) to confirm the outputs.
How to Answer OOP Questions
A good interview answer usually has three parts:
Definition in one or two sentences.
Example — real-world and/or a few lines of code.
Why it matters — the benefit or the trade-off.
For example, "What is encapsulation?" → "Bundling data with the methods that operate on it and restricting direct access to the data. For example, a BankAccount keeps balance private and only allows changes through deposit() and withdraw(), which validate the amount. This protects the object's invariants and lets us change the internal representation without breaking callers."
Basics of OOP
See Introduction to OOP, Procedural vs Object-Oriented Programming and Classes & Objects.
1. What is Object-Oriented Programming?
A programming paradigm that organises software around objects — units that combine data (state) and the code that works on that data (behaviour) — rather than around functions and a separate flow of data. Programs are built from objects that interact by calling each other's methods.
2. What are the four pillars of OOP?
Encapsulation (bundle data + methods, hide internal state), Abstraction (expose what an object does, hide how), Inheritance (a class acquires properties and behaviour of another), and Polymorphism (one interface, many implementations).
3. What is the difference between a class and an object?
A class is a blueprint or user-defined type that describes attributes and methods; it is declared once. An object is an instance of a class created at run time; it occupies memory and has its own state. One class, many objects — like one house plan and many houses.
4. How is OOP different from procedural programming?
Procedural programming organises code into functions that operate on shared data, with a top-down design (C). OOP binds data and functions into objects with a bottom-up design, uses access control to protect data, and supports inheritance and polymorphism for reuse and extension (Java, C++). OOP scales better for large, changing systems; procedural code can be simpler for small tasks.
5. Is Java a 100% (pure) object-oriented language?
No. It has primitive types (int, char, boolean...) that are not objects, and static members that can be used without any object. Languages like Smalltalk, where everything is an object, are called pure OOP languages. Wrapper classes (Integer etc.) let primitives be used as objects when needed.
6. How much memory does a class occupy?
A class definition itself doesn't occupy memory for instance data; objects do. In Java the class's metadata and static fields are stored once by the JVM; each object stores its own instance fields on the heap.
Constructors and Object Lifecycle
See Constructors & Destructors, Object Lifecycle & Memory and Shallow Copy vs Deep Copy.
7. What is a constructor? How is it different from a method?
A special member that initialises a new object. It has the same name as the class, has no return type (not even void), is called automatically on creation, and is not inherited. A method has a return type, any name, and is called explicitly.
8. What are the types of constructors?
Default (no-argument, provided by the compiler only if you write no constructor), parameterised, and in C++ the copy constructor (and move constructor). Java has no built-in copy constructor, but you can write one yourself, e.g. Student(Student other).
9. Can a constructor be private? Why would you do that?
Yes. It prevents other classes from creating objects directly. Used in Singleton, in utility classes with only static methods (like java.lang.Math), and in classes that force creation through static factory methods or a Builder.
10. What is constructor chaining?
One constructor calling another: this(...) calls another constructor of the same class, super(...) calls a parent constructor. Either must be the first statement. If you write neither, Java inserts super() automatically, so parent constructors always run before child constructors.
11. What is a destructor? Does Java have one?
A destructor (C++ ~ClassName()) runs automatically when an object is destroyed, typically to free resources (RAII). Java has no destructors; unreachable objects are reclaimed by the garbage collector at an unpredictable time. finalize() is deprecated for removal; use try-with-resources with AutoCloseable (or Cleaner) for cleanup.
12. Shallow copy vs deep copy?
A shallow copy copies field values, so referenced objects are shared between the original and the copy. A deep copy also copies the referenced objects recursively, so the two are fully independent. Java's default Object.clone() is shallow.
Encapsulation, Abstraction and Access Control
See Encapsulation, Abstraction, Access Modifiers and Static vs Instance Members.
13. What is the difference between encapsulation and abstraction?
Abstraction is a design idea: show only the essential operations and hide complexity (what an object does). Encapsulation is an implementation technique: bundle data with methods and restrict access to the data (how we protect it). Example: a car's steering and pedals are the abstraction; the sealed engine bay that you can't tamper with is encapsulation.
14. How do you achieve encapsulation in Java?
Make fields private, expose behaviour through public methods (including getters/setters only where needed), and validate inputs inside those methods. Immutable classes (final fields, no setters) are the strongest form.
15. What are the access modifiers in Java and C++?
Java: private (class only), default/package-private (same package), protected (same package + subclasses), public (everywhere). C++: private, protected, public, plus friend to grant a specific function or class access to private members. Members of a C++ class are private by default, of a struct public by default.
16. Static vs instance members?
Instance members belong to each object (each object has its own copy of instance fields). Static members belong to the class (one shared copy) and can be used without creating an object. A static method cannot directly access instance members, because there is no this.
17. Why is main() static in Java?
main() static in Java?So the JVM can call it without creating an object of the class first — there is no object yet when the program starts.
Inheritance
See Inheritance and Types of Inheritance.
18. What is inheritance and why is it used?
A mechanism where a child class acquires the fields and methods of a parent class, forming an "is-a" relationship (Car is a Vehicle). It enables code reuse and is the basis of runtime polymorphism.
19. What are the types of inheritance?
Single, multilevel, hierarchical, multiple and hybrid. Java classes support single, multilevel and hierarchical; multiple inheritance is possible only through interfaces. C++ and Python support all types.
20. Why doesn't Java support multiple inheritance of classes?
To avoid the diamond problem: if B and C both extend A and override a method, and D extends both, it is ambiguous which version D inherits, and whether D holds one or two copies of A's fields. Java avoids state ambiguity by allowing multiple inheritance only of interfaces; if two interfaces give conflicting default methods, the class must override the method (and can call A.super.m()).
21. How does C++ solve the diamond problem?
With virtual inheritance: class B : virtual public A and class C : virtual public A make D contain a single shared A subobject. Ambiguous member functions still need to be resolved by overriding or qualifying (B::f()).
22. Is-a vs has-a?
Is-a is inheritance (Dog is an Animal). Has-a is association/aggregation/composition (Car has an Engine). Prefer has-a when the relationship isn't a true subtype relationship — "favour composition over inheritance".
23. Which members are not inherited in Java?
Constructors are not inherited. Private members exist in the child object but are not accessible by name in the child. Static methods are accessible through the child but are not overridden (they can only be hidden).
Polymorphism
See Polymorphism and Method Overloading vs Method Overriding.
24. What is polymorphism? What are its types?
The ability of one interface or name to take many forms. Compile-time (static): method overloading, and operator overloading in C++; the call is resolved by the compiler. Run-time (dynamic): method overriding with a parent reference pointing to a child object; the call is resolved at run time by the object's actual type.
25. Overloading vs overriding?
Overloading: same method name, different parameter lists, usually in the same class; resolved at compile time; return type alone cannot distinguish overloads. Overriding: a subclass redefines a parent method with the same signature; resolved at run time; cannot reduce visibility; a covariant (subtype) return type is allowed.
26. Can we override static, private or final methods in Java?
No. Static methods are hidden, not overridden (the call depends on the reference type). Private methods are not visible to the child, so a same-named method is a new method. Final methods cannot be overridden by design.
27. What is dynamic method dispatch / dynamic binding?
The mechanism by which a call to an overridden method through a parent-type reference is resolved at run time based on the actual object. In C++ it happens only for virtual functions and is usually implemented with a vtable (a per-class table of function pointers) and a hidden vptr in each object. In Java, non-static, non-private, non-final methods are virtual by default.
28. Does Java support operator overloading?
Not for user-defined types. The only built-in overload is + for string concatenation. C++ and Python support operator overloading (operator+, __add__).
Abstract Classes and Interfaces
See Abstraction and Abstract Classes vs Interfaces.
29. Abstract class vs interface in Java?
An abstract class can have instance fields, constructors, and methods of any visibility; a class can extend only one. An interface has only constants (no instance state), can have abstract, default, static and private methods, and a class can implement many. Use an abstract class for a shared base with common state; use an interface for a capability or contract.
30. Can an abstract class have a constructor? Can we instantiate it?
It can have a constructor, which runs when a subclass object is created (via super()). It cannot be instantiated directly with new; new Shape() { ... } creates an anonymous subclass, not the abstract class itself.
31. What is a pure virtual function in C++?
A virtual function declared with = 0, e.g. virtual double area() const = 0;. A class with at least one pure virtual function is abstract and cannot be instantiated. A C++ "interface" is a class with only pure virtual functions (and a virtual destructor).
32. Can an abstract class exist without any abstract methods?
Yes, in Java you can declare abstract class X with only concrete methods, simply to prevent direct instantiation.
Relationships and Design Quality
See Association, Aggregation & Composition, Coupling & Cohesion and UML Class Diagrams.
33. Association vs aggregation vs composition?
Association: any long-lived link between objects (teacher–student). Aggregation: whole–part where the part can exist independently (department–professor), UML hollow diamond. Composition: whole–part where the part's lifetime depends on the whole and it belongs to only one whole (house–room), UML filled diamond.
34. What are coupling and cohesion? What do we want?
Coupling is how much one module depends on others; cohesion is how closely the responsibilities inside one module belong together. We want low coupling and high cohesion, which makes code easier to change, test and reuse.
35. Why "favour composition over inheritance"?
Inheritance creates tight, compile-time coupling and exposes parent internals (fragile base class problem). Composition lets behaviour be swapped at run time, keeps classes small and loosely coupled, and avoids deep hierarchies. Use inheritance only for genuine is-a relationships that satisfy Liskov substitution.
SOLID Principles
See the three SOLID chapters.
36. What does SOLID stand for?
Single Responsibility (a class should have one reason to change), Open/Closed (open for extension, closed for modification), Liskov Substitution (subtypes must be usable wherever the base type is expected without breaking correctness), Interface Segregation (clients shouldn't depend on methods they don't use), Dependency Inversion (high-level modules depend on abstractions, not concrete low-level modules).
37. Give a classic example of an LSP violation.
Square extends Rectangle: setting width on a square also changes its height, so code that expects a rectangle (set width 5, height 4, expect area 20) breaks. Another: Penguin extends Bird where Bird has fly().
38. Dependency Inversion vs Dependency Injection?
Dependency Inversion is a design principle: depend on abstractions. Dependency Injection is a technique for following it: an object receives its dependencies (through the constructor, a setter or a framework) instead of creating them with new.
Design Patterns and UML
See Introduction to Design Patterns and the three pattern chapters.
39. What are design patterns and their categories?
Reusable solutions to recurring design problems. The 23 Gang of Four patterns are creational (5), structural (7) and behavioral (11).
40. Write a thread-safe Singleton in Java.
Simplest robust option: enum Config { INSTANCE; }. Lazy class-based option: the holder idiom — a private static class Holder { static final Config INSTANCE = new Config(); } and getInstance() returns Holder.INSTANCE. If you use double-checked locking, the field must be volatile.
41. Factory Method vs Abstract Factory vs Builder?
Factory Method: a subclass decides which single product to create. Abstract Factory: an object creates a family of related products. Builder: assembles one complex object step by step, often immutable, avoiding long constructors.
42. Adapter vs Decorator vs Facade?
Adapter converts one interface into another. Decorator keeps the same interface and adds behaviour, and can be stacked. Facade gives one simple interface to a complex subsystem.
43. Observer vs Strategy vs Command?
Observer: a subject notifies many dependents when it changes. Strategy: interchangeable algorithms behind one interface. Command: a request wrapped as an object, enabling undo/redo and queuing.
44. How are inheritance and interface implementation shown in UML?
Inheritance (generalization): solid line with a hollow triangle pointing to the parent. Implementation (realization): dashed line with a hollow triangle pointing to the interface.
Language-Specific Questions
45. Why should a base class destructor be virtual in C++?
If you delete a derived object through a base-class pointer and the base destructor is not virtual, the behaviour is undefined — in practice usually only the base destructor runs, leaking the derived part's resources. Any class meant to be used polymorphically should have a virtual destructor.
46. What is object slicing in C++?
When a derived object is copied into a base-class object (by value), only the base part is copied; the derived part and its overrides are "sliced off". Pass polymorphic objects by reference or pointer to avoid it. Java has no slicing because objects are always accessed through references.
47. How does Python handle access modifiers?
Python has no enforced access control. By convention, _name means internal; __name triggers name mangling to _ClassName__name, which avoids accidental clashes in subclasses but does not make it truly private.
48. What is MRO in Python?
The Method Resolution Order — the order in which Python searches base classes for an attribute. Python 3 computes it with the C3 linearization algorithm; you can see it with ClassName.__mro__ or ClassName.mro().
49. Is Java pass-by-value or pass-by-reference?
Always pass-by-value. For objects, the value passed is a copy of the reference, so a method can modify the object it refers to but cannot make the caller's variable point to a different object.
50. What is the contract between equals() and hashCode()?
equals() and hashCode()?If two objects are equal according to equals(), they must return the same hashCode(). Override both together; otherwise hash-based collections like HashSet and HashMap behave incorrectly.
Predict the Output
These are favourites in written tests and technical rounds. Work out the answer on paper first.
Question A: Field hiding, static methods and overriding
class Parent {
String name = "Parent field";
static void greet() { System.out.println("static greet in Parent"); }
void show() { System.out.println("show in Parent"); }
}
class Child extends Parent {
String name = "Child field";
static void greet() { System.out.println("static greet in Child"); }
@Override
void show() { System.out.println("show in Child"); }
}
class Main {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.name);
p.greet();
p.show();
}
}Show output and explanation
Output:
Parent field
static greet in Parent
show in ChildFields and static methods are resolved using the reference type (Parent) at compile time: fields are hidden, not overridden, and static methods are hidden too (calling a static method through a reference is legal but misleading). Only the instance method show() is dynamically dispatched to the actual object (Child).
Question B: Overload resolution
class Main {
static void print(Object o) { System.out.println("Object version"); }
static void print(String s) { System.out.println("String version"); }
static void print(long x) { System.out.println("long version"); }
public static void main(String[] args) {
print(null);
print(5);
print('A');
}
}Show output and explanation
Output:
String version
long version
long versionnull fits both Object and String; Java picks the most specific type, String. (If there were also a print(Integer), the call would be ambiguous and would not compile.) For 5 and 'A', Java first tries overloads that need no boxing: int → long and char → long are widening conversions, so long wins over boxing to Integer/Character and then upcasting to Object. Order of preference: exact match, widening, boxing, varargs.
Question C: Calling an overridable method from a constructor
class Base {
Base() {
System.out.println("Base constructor");
describe();
}
void describe() { System.out.println("Base.describe"); }
}
class Derived extends Base {
private int level = 5;
Derived() {
System.out.println("Derived constructor, level = " + level);
}
@Override
void describe() { System.out.println("Derived.describe, level = " + level); }
}
class Main {
public static void main(String[] args) {
new Derived();
}
}Show output and explanation
Output:
Base constructor
Derived.describe, level = 0
Derived constructor, level = 5The Base constructor runs first (implicit super()). Inside it, describe() is dynamically dispatched to Derived's version, but Derived's field initialisers (level = 5) haven't run yet, so level still has its default value 0. Lesson: never call overridable methods from a constructor.
Question D: equals() without hashCode()
import java.util.HashSet;
import java.util.Set;
class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
// hashCode() is NOT overridden
}
class Main {
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
Set<Point> set = new HashSet<>();
set.add(a);
set.add(b);
System.out.println(a.equals(b));
System.out.println(set.size());
}
}Show output and explanation
Output:
true
2The objects are equal, but they inherit Object.hashCode(), which almost always differs for two distinct objects. HashSet uses the hash code first to find the bucket, so it never compares the two with equals() and stores both. Overriding hashCode() (for example Objects.hash(x, y)) makes the size 1.
Question E: Static counter and pass-by-value
class Counter {
static int created = 0;
int id;
Counter() { created++; id = created; }
}
class Main {
static void reassign(StringBuilder sb) {
sb.append(" World");
sb = new StringBuilder("New");
sb.append("!!");
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println(c1.id + " " + c3.id + " " + Counter.created);
StringBuilder sb = new StringBuilder("Hello");
reassign(sb);
System.out.println(sb);
}
}Show output and explanation
Output:
1 3 3
Hello Worldcreated is static, so all three constructors increment the same counter; each object stores the value at its creation time in its own id. In reassign(), sb is a copy of the reference: append(" World") changes the shared object, but sb = new StringBuilder("New") only changes the local copy, so the caller never sees "New!!".
Question F (C++): Object slicing and virtual destructors
#include <iostream>
class Animal {
public:
virtual void speak() const { std::cout << "Animal sound\n"; }
virtual ~Animal() { std::cout << "~Animal\n"; }
};
class Dog : public Animal {
public:
void speak() const override { std::cout << "Woof\n"; }
~Dog() override { std::cout << "~Dog\n"; }
};
void byValue(Animal a) { a.speak(); } // copies only the Animal part (slicing)
void byRef(const Animal& a) { a.speak(); } // no copy, dynamic dispatch works
int main() {
Dog d;
byValue(d);
byRef(d);
Animal* p = new Dog();
delete p;
std::cout << "end of main\n";
}Show output and explanation
Output:
Animal sound
~Animal
Woof
~Dog
~Animal
end of main
~Dog
~AnimalbyValue(d)copies only theAnimalpart (slicing), soAnimal soundis printed, and the temporary copy is destroyed at the end of the call (~Animal).byRef(d)passes a reference, so virtual dispatch works:Woof.delete pruns~Dogthen~Animalbecause the destructor isvirtual. Withoutvirtualon~Animal, thisdeletewould be undefined behaviour.When
mainends, the localdis destroyed:~Dog, then~Animal(derived first, base last — the reverse of construction).
Question G (Python): Diamond inheritance and MRO
class A:
def hello(self):
return "A"
class B(A):
def hello(self):
return "B"
class C(A):
def hello(self):
return "C"
class D(B, C):
pass
print(D().hello())
print([cls.__name__ for cls in D.__mro__])Show output and explanation
Output:
B
['D', 'B', 'C', 'A', 'object']Python resolves the diamond using the C3 MRO: D, then its bases left to right (B, C), then the common base A, then object. The first class in that order defining hello is B. Writing class D(C, B) would print C.
Quick Revision Table
Concept | One-line answer |
|---|---|
Encapsulation | Data + methods together, data hidden behind methods |
Abstraction | Show what, hide how |
Inheritance | Child reuses parent; is-a |
Polymorphism | One interface, many forms; overloading (compile time), overriding (run time) |
Abstract class vs interface | Shared base with state vs contract/capability; extend one, implement many |
Aggregation vs composition | Part can live alone (◇) vs part dies with whole (◆) |
Coupling / cohesion | Want low coupling, high cohesion |
SOLID | SRP, OCP, LSP, ISP, DIP |
GoF patterns | 23 = 5 creational + 7 structural + 11 behavioral |
C++ must-knows |
|
Java must-knows | Pass-by-value, no multiple class inheritance, |
Common Mistakes in Interviews
Mixing up abstraction and encapsulation — give the "what vs how" and "design vs implementation" distinction.
Saying Java is pass-by-reference for objects. It passes references by value.
Saying static methods can be overridden. They are hidden.
Saying interfaces can't have method bodies. Since Java 8 they can have
defaultandstaticmethods, and since Java 9privatemethods.Calling overloading "runtime polymorphism". Overloading is resolved at compile time.
Giving only definitions. Always add an example and a reason.
Summary
Answer with definition, example and why.
Master the four pillars, constructors and object lifecycle, inheritance rules (and the diamond problem), the two kinds of polymorphism, and abstract classes vs interfaces.
Know relationships (association, aggregation, composition), coupling and cohesion, and SOLID with one example each.
Be able to code a thread-safe Singleton and explain Factory, Builder, Adapter, Decorator, Facade, Observer, Strategy and Command.
Practise "predict the output" questions on hiding vs overriding, overload resolution, constructor order,
equals/hashCode, pass-by-value, slicing and MRO.
That completes the OOP tutorial. Revisit any chapter whose questions you found difficult, then try designing a small system (a library, a parking lot or a food-delivery app) end-to-end: classes, relationships, a UML class diagram and one or two patterns where they genuinely help.