Practice commonly asked
OOP interview questions with clear answers and explanations.
30
Interview Questions
Questions & Answers
OOP Interview Questions
30 Questions
Q 31
What is an Abstract Method and can an abstract class have zero abstract methods?
Easy
Answer
An abstract method is a method declared without an implementation body (ending with a semicolon). An abstract class CAN have zero abstract methods; declaring a class abstract simply prevents direct instantiation.
Explanation
If a class contains even a single abstract method, the class MUST be declared abstract.
Code Example
Java
abstract class BaseService {
// Valid abstract class with NO abstract methods
void commonHelper() {
System.out.println("Re-usable logic for subclasses only");
}
}
Reference:
Java OOP Concepts
Q 32
What is the purpose of Object class methods: equals(), hashCode(), toString(), and clone()?
Easy
Answer
Object is the ultimate root superclass of every class in Java. equals() checks logical object equality; hashCode() computes memory hash buckets for hash tables; toString() returns readable textual representations; and clone() performs shallow field copying.
Explanation
Classes should always override equals(), hashCode(), and toString() for accurate value comparison, hash structure compatibility, and debugging logs.
Code Example
Java
class Item {
int id;
String name;
@Override
public String toString() { return "Item{id=" + id + ", name='" + name + "'}"; }
}
Reference:
Java OOP Concepts
Q 33
What is the Builder Design Pattern and when should it be preferred over constructors?
Medium
Answer
The Builder pattern separates the construction of a complex object from its representation, allowing step-by-step object creation. It is preferred when a class has many optional fields to avoid telescoping constructors.
Explanation
Builder patterns produce immutable objects cleanly and provide fluent, readable method chaining syntax.
Code Example
Java
public class HttpRequest {
private final String url, method, body;
private HttpRequest(Builder b) { this.url = b.url; this.method = b.method; this.body = b.body; }
public static class Builder {
private String url, method = "GET", body;
public Builder(String url) { this.url = url; }
public Builder method(String m) { this.method = m; return this; }
public HttpRequest build() { return new HttpRequest(this); }
}
}
Reference:
Java OOP Concepts
Q 34
What is the Observer Design Pattern in Java?
Medium
Answer
The Observer pattern defines a one-to-many dependency between objects so that when one object (Subject) changes state, all its registered dependents (Observers) are notified and updated automatically.
Explanation
Observer pattern is fundamental to event-driven architectures, GUI listeners, and reactive stream pipelines.
Code Example
Java
interface Observer { void update(String news); }
class NewsAgency {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer o) { observers.add(o); }
public void notifyAll(String news) { observers.forEach(o -> o.update(news)); }
}
Reference:
Java OOP Concepts
Q 35
What is the Decorator Design Pattern in Java?
Hard
Answer
The Decorator pattern attaches additional responsibilities to an object dynamically at runtime using composition and inheritance of a common interface, providing a flexible alternative to subclassing.
Explanation
Java I/O streams (e.g. BufferedReader wrapping FileReader) are the classic JDK example of the Decorator pattern.
Code Example
Java
interface Coffee { double getCost(); }
class SimpleCoffee implements Coffee { public double getCost() { return 5.0; } }
class MilkDecorator implements Coffee {
private final Coffee coffee;
public MilkDecorator(Coffee c) { this.coffee = c; }
public double getCost() { return coffee.getCost() + 2.0; }
}
Reference:
Java OOP Concepts
Q 36
What is the Strategy Design Pattern and how does it demonstrate OOP Polymorphism?
Medium
Answer
The Strategy pattern defines a family of interchangeable algorithms, encapsulates each one inside a separate class implementing a common interface, and allows client code to switch algorithms dynamically at runtime.
Explanation
Strategy pattern completely eliminates long switch/if-else blocks by using runtime polymorphic method execution.
Code Example
Java
interface PaymentStrategy { void pay(double amt); }
class UpiPayment implements PaymentStrategy { public void pay(double a) { System.out.println("UPI: " + a); } }
class CardPayment implements PaymentStrategy { public void pay(double a) { System.out.println("Card: " + a); } }
class ShoppingCart {
public void checkout(PaymentStrategy strategy, double amount) {
strategy.pay(amount); // Polymorphic dispatch
}
}
Reference:
Java OOP Concepts
Q 37
What is the Factory Method Design Pattern in Java OOP?
Medium
Answer
The Factory Method pattern defines an interface or method for creating an object, but allows subclasses or factory methods to alter the type of objects that will be created, promoting loose coupling.
Explanation
Factory methods encapsulate object creation logic and prevent calling code from tightly binding to specific concrete constructors.
Code Example
Java
interface Logger { void log(String msg); }
class ConsoleLogger implements Logger { public void log(String m) { System.out.println(m); } }
class LoggerFactory {
public static Logger getLogger(String type) {
if ("console".equalsIgnoreCase(type)) return new ConsoleLogger();
throw new IllegalArgumentException("Unknown type");
}
}
Reference:
Java OOP Concepts
Q 38
What is the Singleton Design Pattern and how is it implemented using thread-safe Enum or Double-Checked Locking in Java?
Hard
Answer
The Singleton pattern ensures a class has only one instance and provides a global access point to it. An Enum singleton is the most robust implementation as it provides guaranteed serialization and reflection protection out of the box.
Explanation
Double-checked locking requires the instance field to be declared 'volatile' to prevent instruction reordering bugs during lazy initialization.
Why can an Interface contain static and default methods in Java 8+, but cannot contain instance variables?
Hard
Answer
Default and static methods provide behavior without state. Interfaces are designed to define contracts and stateless behavioral capabilities; allowing instance variables would re-introduce multiple inheritance state collision (the diamond problem with state).
Explanation
All fields declared in an interface are implicitly 'public static final' constants, ensuring interfaces remain stateless.
Code Example
Java
interface Validator {
int MAX_LIMIT = 100; // implicitly public static final
default boolean isValid(int val) { return val <= MAX_LIMIT; }
static void logInfo() { System.out.println("Validator v1.0"); }
}
Reference:
Java OOP Concepts
Q 40
What is Constructor Overloading and Constructor Chaining using this()?
Easy
Answer
Constructor overloading allows defining multiple constructors with different argument lists within the same class. Constructor chaining with this() allows one constructor to invoke another within the same class to reduce duplicated initialization logic.
Explanation
this() must always be the very first statement inside a constructor body.
Code Example
Java
public class Student {
private String name;
private int age;
public Student(String name) {
this(name, 18); // Chains to two-argument constructor
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Reference:
Java OOP Concepts
Q 41
What is the difference between Static Nested Classes and Non-Static Inner Classes?
Medium
Answer
A static nested class does not hold an implicit reference to an outer class instance and can be instantiated independently. A non-static inner class holds an implicit reference to its enclosing outer instance and can access outer instance members directly.
Explanation
Non-static inner classes can lead to memory leaks in long-lived contexts if they prevent outer class instances from being garbage-collected.
Code Example
Java
class Outer {
static class StaticNested {}
class Inner {}
}
// Instantiation syntax:
Outer.StaticNested s = new Outer.StaticNested();
Outer.Inner i = new Outer().new Inner();
Reference:
Java OOP Concepts
Q 42
What is an Anonymous Inner Class in Java and how does it relate to OOP interfaces?
Medium
Answer
An anonymous inner class is an inline, unnamed class declared and instantiated simultaneously to override methods of an interface or extend an abstract class on the fly.
Explanation
For single-abstract-method (SAM) interfaces, anonymous classes have largely been replaced by concise Lambda expressions in modern Java.
Code Example
Java
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous class running");
}
};
new Thread(r).start();
Reference:
Java OOP Concepts
Q 43
How does Pattern Matching for instanceof (Java 16+) enhance OOP type checking?
Easy
Answer
Pattern matching for instanceof combines type checking and conditional variable extraction into a single statement, eliminating boilerplate explicit type casting.
Explanation
The pattern variable is scoped only to the conditional block where the instanceof evaluation evaluates to true.
Code Example
Java
// Traditional approach:
// if (obj instanceof String) { String s = (String) obj; System.out.println(s.length()); }
// Modern Pattern Matching (Java 16+):
if (obj instanceof String s) {
System.out.println(s.length()); // 's' is automatically cast and bound
}
Reference:
Java OOP Concepts
Q 44
What is the difference between a Copy Constructor and Object.clone() in Java?
Medium
Answer
A copy constructor is a specialized constructor that creates a new object using an existing instance of the same class. Object.clone() is a legacy mechanism requiring Cloneable implementation and type casting, often prone to shallow copy issues and CloneNotSupportedException.
Explanation
Copy constructors are preferred because they do not require type casting, work smoothly with final fields, and avoid the flaws of Cloneable.
Code Example
Java
public class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
// Copy Constructor:
public Point(Point other) {
this(other.x, other.y);
}
}
Reference:
Java OOP Concepts
Q 45
What are Non-Sealed Classes in Java 17+ and when are they used?
Hard
Answer
A 'non-sealed' class explicitly re-opens a sealed class hierarchy for unrestricted extension by any unknown subclass, breaking the closed hierarchy at that specific node.
Explanation
Direct subclasses of a sealed class must declare one of three modifiers: 'final' (no further inheritance), 'sealed' (restricted inheritance), or 'non-sealed' (open inheritance).
Code Example
Java
public sealed interface Vehicle permits Car, Truck {}
public non-sealed class Car implements Vehicle {} // Anyone can extend Car
public class ElectricCar extends Car {} // Valid unrestricted subclass
Reference:
Java OOP Concepts
Q 46
What is the Interface Segregation Principle (ISP)?
Medium
Answer
ISP states that clients should not be forced to depend upon interfaces they do not use. Large, bloated interfaces should be split into smaller, more specific and cohesive role interfaces.
Explanation
A MultiFunctionPrinter interface with print(), scan(), and fax() forces a simple BasicPrinter to implement empty or unsupported stub methods. Splitting into Printable and Scannable solves this.
What is the Dependency Inversion Principle (DIP) and how does it relate to Inversion of Control (IoC)?
Hard
Answer
DIP states that high-level modules should not depend on low-level modules; both should depend on abstractions (interfaces). IoC is the architectural pattern of delegating object creation and dependency wiring to an external container or framework.
Explanation
Dependency Injection (DI) is the primary technique used to implement DIP and IoC in modern Java applications (e.g. Spring Framework).
Code Example
Java
interface NotificationService {
void send(String message);
}
class EmailNotification implements NotificationService {
public void send(String msg) { System.out.println("Email: " + msg); }
}
class OrderProcessor {
private final NotificationService notifier; // Depends on abstraction, not concrete class
public OrderProcessor(NotificationService notifier) { this.notifier = notifier; }
}
Reference:
Java OOP Concepts
Q 48
What is the Open/Closed Principle (OCP) and how is it implemented using OOP polymorphism?
Hard
Answer
The Open/Closed Principle states that software entities (classes, modules) should be open for extension, but closed for modification. It is achieved by coding against interfaces or abstract classes rather than concrete implementations.
Explanation
Instead of using switch/if-else statements to handle new shapes or payment types (which require modifying existing code), add new classes implementing a common interface.
Code Example
Java
interface DiscountStrategy {
double apply(double amount);
}
class FestiveDiscount implements DiscountStrategy {
public double apply(double amount) { return amount * 0.8; }
}
class CheckoutService {
double calculateTotal(double amt, DiscountStrategy strategy) {
return strategy.apply(amt); // Open to new discount types without editing this class
}
}
Reference:
Java OOP Concepts
Q 49
Can we override a private or static method in Java?
Easy
Answer
No. Private methods are not visible to subclasses and are bonded statically at compile-time. Static methods are bound to the class rather than the object instance, so redeclaring them in a subclass results in Method Hiding, not Method Overriding.
Explanation
Applying the @Override annotation on a private or static method causes a compilation error in Java.
What is the difference between Aggregation and Composition, and how is object lifecycle managed in each?
Medium
Answer
In Aggregation (weak HAS-A), the contained object can exist independently of the container class (independent lifecycle). In Composition (strong HAS-A), the contained object cannot exist without the container class (co-dependent lifecycle).
Explanation
When a University is deleted, Departments may be destroyed (Composition), but independent Professors (Aggregation) continue to exist.
Code Example
Java
class Professor {}
class Department {
private List<Professor> professors; // Aggregation (Professors exist outside)
}
class University {
private final List<Department> departments = new ArrayList<>(); // Composition
}
Reference:
Java OOP Concepts
Q 51
Why should object fields generally not be declared public in Java?
Easy
Answer
Declaring fields public breaks Encapsulation by exposing internal state to arbitrary external modification without validation, validation hooks, or access logging, creating tight coupling and fragile architectures.
Explanation
Private fields combined with getter and setter methods allow validation logic, immutable views, and internal data restructuring without breaking calling client code.
Code Example
Java
class User {
private int age; // Protected state
public void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
this.age = age;
}
public int getAge() { return age; }
}
Reference:
Java OOP Concepts
Q 52
How does the Template Method Design Pattern leverage OOP Polymorphism and Abstraction?
Hard
Answer
The Template Method pattern defines the skeletal steps of an algorithm in an abstract base class method (often final), delegating specific step implementations to abstract methods implemented in subclasses.
Explanation
It enforces the overall algorithm sequence in the parent class while allowing subclasses to alter specific steps without changing the algorithm's structure.
What is the difference between Static Binding (Early Binding) and Dynamic Binding (Late Binding)?
Medium
Answer
Static Binding resolves method calls at compile-time based on reference types (private, final, and static methods). Dynamic Binding resolves method calls at runtime based on the actual object instance (overridden instance methods).
Explanation
Because private, static, and final methods cannot be overridden, the compiler binds them early for faster execution.
Code Example
Java
class Test {
private void display() { System.out.println("Private"); } // Static binding
public void show() { System.out.println("Public"); } // Dynamic binding
}
Reference:
Java OOP Concepts
Q 54
What is Liskov Substitution Principle (LSP) and how is it violated?
Hard
Answer
LSP states that objects of a superclass should be replaceable with objects of a subclass without altering the correctness or functionality of the program.
Explanation
Classic violation: A Square extending Rectangle where setting width modifies height breaks expectation of Rectangle callers.
Code Example
Java
class Rectangle {
protected int width, height;
public void setWidth(int w) { this.width = w; }
public void setHeight(int h) { this.height = h; }
public int getArea() { return width * height; }
}
class Square extends Rectangle {
@Override
public void setWidth(int w) { this.width = this.height = w; } // Violates LSP!
}
Reference:
Java OOP Concepts
Q 55
What are SOLID principles in Object-Oriented Design?
These 5 principles form the foundation of maintainable, scalable, and testable object-oriented software architectures.
Code Example
Java
// Single Responsibility: Class only does report generation
class ReportGenerator {
public String generateReport() { return "Report Data"; }
}
// Separate class handles persistence (SRP)
class ReportRepository {
public void save(String report) { /* Save DB */ }
}
Reference:
Java OOP Concepts
Q 56
What is the difference between Tight Coupling and Loose Coupling in Java design?
Medium
Answer
Tight coupling occurs when a class directly depends on concrete class implementations, making changes disruptive. Loose coupling occurs when classes interact via interfaces or abstractions, reducing interdependency and enhancing testability.
Explanation
Loose coupling is achieved via Dependency Injection and coding to interfaces rather than concrete classes.
Code Example
Java
// Tightly Coupled:
class OrderService {
private MySQLDatabase db = new MySQLDatabase(); // Hard-coded dependency
}
// Loosely Coupled:
class OrderServiceLoose {
private final Database db;
public OrderServiceLoose(Database db) { this.db = db; } // Injected via Interface
}
Reference:
Java OOP Concepts
Q 57
What is a Marker (Tagging) Interface in Java and how is it used?
Easy
Answer
A Marker Interface is an interface with no methods or constants (e.g. Serializable, Cloneable, Remote). It acts as a metadata tag informing the JVM or framework that implementing classes possess specific runtime capabilities.
Explanation
In modern Java, Custom Annotations have largely replaced marker interfaces for attaching metadata to classes.
Code Example
Java
public class UserProfile implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String username;
// Indicates JVM can serialize this class to byte streams
}
Reference:
Java OOP Concepts
Q 58
What is the difference between an Association, Aggregation, and Composition in OOP?
Hard
Answer
Association represents a general relationship between two classes. Aggregation is a weak 'HAS-A' relationship where child objects can exist independently of the parent (e.g., Department and Teacher). Composition is a strong 'HAS-A' relationship where child objects cannot exist without the parent lifecycle (e.g., House and Room).
Explanation
In Composition, deleting the parent object destroys the constituent child objects. In Aggregation, child objects survive parent deletion.
Code Example
Java
// Aggregation: Teacher exists independently
class Teacher {}
class Department { List<Teacher> teachers; }
// Composition: Room dies if House is destroyed
class House {
private final Room room = new Room();
}
Reference:
Java OOP Concepts
Q 59
What are Record classes in modern Java (Java 14+) and how do they relate to OOP encapsulation?
Medium
Answer
Records are immutable data carriers that automatically generate private final fields, a canonical constructor, getters (accessors), equals(), hashCode(), and toString() boilerplate based on class header components.
Explanation
Records cannot extend other classes (they implicitly extend java.lang.Record), are implicitly final, but can implement interfaces and declare custom constructors (compact constructors).
Code Example
Java
public record Point(int x, int y) {
// Compact constructor with validation
public Point {
if (x < 0 || y < 0) throw new IllegalArgumentException("Coordinates must be positive");
}
}
// Usage:
Point p = new Point(10, 20);
System.out.println(p.x()); // Accessor method
Reference:
Java OOP Concepts
Q 60
What are Sealed Classes and Interfaces introduced in modern Java (Java 17+)?
Hard
Answer
Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them using the 'sealed' and 'permits' keywords, enabling controlled domain modeling.
Explanation
Subclasses of a sealed class must be explicitly declared as 'final', 'sealed', or 'non-sealed'. It allows exhaustive pattern matching in switch statements without default branches.
Code Example
Java
public sealed interface Shape permits Circle, Rectangle {}
public final class Circle implements Shape {}
public final class Rectangle implements Shape {}
// Exhaustive pattern matching (Java 21+):
String describe(Shape s) {
return switch (s) {
case Circle c -> "Circle";
case Rectangle r -> "Rectangle";
};
}
Reference:
Java OOP Concepts
About This Topic
Prepare for
OOP interviews with important concepts
and commonly asked questions.