LearnFrenzy
Sign in Take a free test

Java Programming interview · Set 8 of 13

Java OOP in Depth: Polymorphism, Interfaces and SOLID

  • 7 follow-up questions
  • 4 key points
  • Code examples
Test yourself

OOP beyond the four pillars

Interviewers want to see design judgement: when to use an interface, how to keep objects immutable, how polymorphism removes if-else chains, and how SOLID shapes real code.

  • MechanicsOverloading, overriding, static and final.
  • AbstractionsInterfaces, abstract classes and dispatch.
  • DesignImmutability, composition and SOLID.

OOP questions are the backbone of every Java interview, from campus rounds to senior roles. Interviewers go past definitions: “what happens if…”, “why would you…”, “design this using…”. The answers below pair each concept with a short, realistic example.

1. Overloading vs overriding — what are the rules?

Overloading means same method name, different parameter lists, in the same class — resolved at compile time. Overriding means a subclass redefines an inherited method with the same signature — resolved at runtime based on the actual object. An override cannot reduce visibility, cannot throw broader checked exceptions, and may return a subtype (covariant return). Always add @Override.

class Notifier {
    void send(String to) { System.out.println("Email to " + to); }
    void send(String to, String text) { System.out.println("Email: " + text); }   // overload
}
class SmsNotifier extends Notifier {
    @Override
    void send(String to) { System.out.println("SMS to " + to); }                 // override
}
Notifier n = new SmsNotifier();
n.send("Asha");     // SMS to Asha — chosen at runtime

2. Abstract class vs interface in modern Java?

An abstract class can hold state (fields), constructors and any mix of abstract and concrete methods; a class can extend only one. An interface defines a contract; since Java 8 it can have default and static methods, and since Java 9 private methods, but no instance state; a class can implement many. Use an interface for capabilities (Comparable, PaymentGateway) and an abstract class for shared base behaviour with state.

interface PaymentGateway {
    String charge(double amount);
    default String currency() { return "INR"; }        // default method
}

abstract class BaseGateway implements PaymentGateway {
    protected final String apiKey;                       // shared state
    BaseGateway(String apiKey) { this.apiKey = apiKey; }
}

class Razorpay extends BaseGateway {
    Razorpay(String key) { super(key); }
    public String charge(double amount) { return "rzp_" + amount; }
}

3. Explain the static and final keywords.

static members belong to the class, not instances — shared counters, constants, utility methods; static methods cannot use this or be overridden (they are hidden). final means: a final variable cannot be reassigned, a final method cannot be overridden, a final class cannot be extended. A static final field is a constant.

public final class AppConfig {               // cannot be subclassed
    public static final int MAX_RETRIES = 3;    // constant
    private static int instances = 0;           // shared by all objects
    private final String env;                   // set once

    public AppConfig(String env) { this.env = env; instances++; }
    public static int instances() { return instances; }
}

4. How do you make a class immutable?

Make the class final, all fields private final, set them only in the constructor, provide no setters, and defensively copy mutable inputs and outputs (lists, dates). Records give you most of this for free. Immutable objects are thread-safe and safe as map keys.

public final class Order {
    private final String id;
    private final List<String> items;

    public Order(String id, List<String> items) {
        this.id = id;
        this.items = List.copyOf(items);      // defensive, unmodifiable copy
    }
    public String id() { return id; }
    public List<String> items() { return items; }   // already unmodifiable
}

5. What is runtime polymorphism and how does dynamic dispatch work?

A parent-type reference can point to any subclass object, and the JVM calls the method of the actual object at runtime through the class's virtual method table. It lets you write code against an abstraction and add new types without changing callers — the core of the Open/Closed principle.

List<Shape> shapes = List.of(new Circle(2), new Square(3));
double total = 0;
for (Shape s : shapes) total += s.area();     // each object's own area() runs

6. Explain the SOLID principles with Java examples.

  • Single responsibility — InvoicePrinter prints, InvoiceRepository saves.
  • Open/closed — add a new PaymentGateway implementation without editing checkout code.
  • Liskov substitution — a subclass must work wherever its parent is expected (a Square that breaks Rectangle's setters violates it).
  • Interface segregation — small focused interfaces instead of one giant one.
  • Dependency inversion — depend on interfaces and inject implementations (what Spring does).

7. What is the difference between composition and aggregation?

Both are “has-a” relationships. In composition the part cannot exist without the whole (an Order and its OrderLines are created and destroyed together). In aggregation the part has its own life (a Department has Employees who exist independently). Prefer composition over inheritance for reuse.


8. How do equals(), hashCode() and toString() relate to good class design?

Value-like classes should override equals and hashCode together (consistently, using the same fields) so they work in sets and maps, and toString for readable logs. Entities with identity (database rows) often compare by id. Records generate all three.

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Employee e)) return false;      // pattern matching for instanceof
    return id == e.id && Objects.equals(email, e.email);
}
@Override
public int hashCode() { return Objects.hash(id, email); }

Remember

Key points

  • Overload at compile time

    Override at runtime.

  • Interfaces for capabilities

    Abstract classes for shared state.

  • Immutable = final + copies

    No setters, defensive copying.

  • Program to interfaces

    The heart of SOLID and Spring.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Can you override a static or private method? Basic

    No. Static methods are hidden, not overridden (resolved by the reference type); private methods are not inherited.

  2. 2 Can an interface have a constructor? Basic

    No — interfaces have no instance state to initialise.

  3. 3 What happens if two interfaces have the same default method? Intermediate

    The class must override it to resolve the conflict, optionally calling InterfaceA.super.method().

  4. 4 What is the diamond problem and how does Java avoid it? Intermediate

    Ambiguity when a class inherits the same member from two paths. Java allows only single class inheritance; for interface default methods it forces the class to resolve conflicts explicitly.

  5. 5 What is a marker interface? Intermediate

    An interface with no methods used to tag classes (Serializable, Cloneable). Annotations usually serve this purpose today.

  6. 6 Why is String final in Java? Intermediate

    So no subclass can break its immutability, which the string pool, security checks and hashing rely on.

  7. 7 What is the difference between this and super? Basic

    this refers to the current object (and calls another constructor of the same class); super refers to the parent part (and calls the parent constructor or overridden method).

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links