Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • About
  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

👥10,009visitors

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsObject-Oriented Programming
✓ FreeBeginner· 9 min read

Abstraction, Interfaces & Encapsulation — Interview Questions

Abstraction and loose coupling, abstract classes vs interfaces (with Java 8/9 changes), default and static interface methods, the diamond problem, Comparable vs Comparator, and encapsulation done right.

Published September 25, 2026


How to use this lesson

"Abstract class vs interface" is probably the most asked OOP question in Java interviews, and many prepared answers are out of date: they still say "interfaces can only have abstract methods". Give the modern answer, and explain when you'd choose each one.

Q1. What is abstraction in Java?

Short answer: Abstraction means exposing what an object does while hiding how it does it. In Java you express it with interfaces and abstract classes: callers depend on the contract, not on the implementation.

public interface PaymentGateway {
    PaymentResult charge(Order order);          // what — the contract
}
class RazorpayGateway implements PaymentGateway {
    public PaymentResult charge(Order order) { /* how — HTTP calls, retries, signatures */ return null; }
}

Learn it in depth → Interfaces and Abstract Classes

Q2. Where is abstraction used in the Java libraries?

Short answer: Everywhere. The Collections Framework is the classic example: you code against List, Map and Set, and you can swap ArrayList for LinkedList without changing the calling code.

Key points to cover:

  • JDBC: Connection, PreparedStatement and ResultSet are interfaces. Each database vendor supplies the implementation.
  • I/O: InputStream and Reader hide whether bytes come from a file, a socket or memory.
  • java.util.concurrent: you submit tasks to an ExecutorService without knowing how its threads are managed.
  • Spring: you inject a JpaRepository, and Spring generates the implementation at runtime.

Q3. What happens if a class contains an abstract method?

Short answer: The class must itself be declared abstract, or it won't compile. An abstract class can't be instantiated with new. A concrete subclass must implement all the abstract methods, or it must be declared abstract as well.

Key points to cover:

  • An abstract class can have constructors (they run when a subclass is created), fields, concrete methods and static methods.
  • An abstract class doesn't have to contain any abstract methods. Declaring it abstract simply prevents instantiation.

Q4. How does abstraction help achieve loose coupling?

Short answer: When a class depends on an interface rather than a concrete class, you can change, replace or mock the implementation without touching the class. Changes stay contained, and testing becomes easy.

class CheckoutService {
    private final PaymentGateway gateway;             // depends on the abstraction
    CheckoutService(PaymentGateway gateway) { this.gateway = gateway; }
}
// production: new CheckoutService(new RazorpayGateway())
// unit test:  new CheckoutService(mock(PaymentGateway.class))

Key points to cover:

  • This is the Dependency Inversion Principle, and it's exactly what Spring's dependency injection automates.

Learn it in depth → Dependency Inversion

Q5. What is an interface in Java?

Short answer: An interface is a reference type that defines a contract: a set of methods that implementing classes must provide. A class can implement many interfaces.

Key points to cover:

  • What an interface can contain:
    • Abstract methods (implicitly public abstract).
    • Constants (implicitly public static final).
    • default and static methods (Java 8).
    • private methods (Java 9).
    • Nested types.
  • It can't have instance fields or constructors.
  • Functional interfaces (with exactly one abstract method) can be implemented with lambdas.
  • Marker interfaces (Serializable, Cloneable) have no methods at all.

Q6. What's the difference between an interface and an abstract class?

Short answer: An abstract class is a partially built parent. It can hold state, constructors and shared code, and a class can extend only one. An interface is a capability contract. It has no instance state, and a class can implement many.

Abstract classInterface
Inheritanceextends one onlyimplements many
Instance fields (state)YesNo (constants only)
ConstructorsYesNo
Method kindsAbstract + concrete (any access level)Abstract, default, static, private
Default access of membersPackage-privatepublic
Typical meaning"is a kind of" (template)"can do" (capability)

Common trap: saying "interfaces give 100% abstraction and can only have abstract methods". That was true before Java 8. Today interfaces can contain default, static and private method bodies. What they still can't have is instance state.

Learn it in depth → Interfaces and Abstract Classes

Q7. When would you use an interface, and when an abstract class?

Short answer:

  • Use an interface to define a role or capability that unrelated classes can share (Comparable, PaymentGateway, Runnable), and whenever you want multiple implementations or easy mocking. It's the default choice.
  • Use an abstract class when several closely related classes share state and code, and you want a template with some steps left for subclasses to fill in.

Key points to cover:

  • A common combination: an interface for the contract, plus an abstract base class with shared plumbing. For example, List and AbstractList in the JDK.
  • In the source material this question also opens up extending a class vs implementing an interface. Extend a class to inherit real behaviour for a true IS-A relationship. Implement an interface to promise capabilities.

Q8. How do you get multiple inheritance using interfaces?

Short answer: A class can implement several interfaces, so it inherits several types. It can be passed wherever any of them is expected.

class SmartCamera implements Recordable, Streamable, AutoCloseable {
    public void record() { }
    public void stream() { }
    public void close() { }
}

Key points to cover:

  • An interface can also extend multiple interfaces: interface Device extends Recordable, Streamable {}.

Q9. Can interfaces have static methods? How do they differ from default methods?

Short answer: Yes, since Java 8.

  • A static interface method belongs to the interface itself. It's called as InterfaceName.method(), and it's not inherited by implementing classes, so it can't be overridden.
  • A default method is an instance method with a body. Implementing classes inherit it and can override it.
public interface Discount {
    BigDecimal apply(BigDecimal price);

    default Discount andThen(Discount next) {            // inherited, overridable
        return price -> next.apply(apply(price));
    }
    static Discount percent(int p) {                     // utility/factory: Discount.percent(10)
        return price -> price.multiply(BigDecimal.valueOf(100 - p)).divide(BigDecimal.valueOf(100));
    }
}

Key points to cover:

  • Default methods were added so existing interfaces could evolve without breaking every implementation. That's how Collection.stream() and Iterable.forEach() were introduced.

Q10. What is the diamond problem, and how does Java handle it?

Short answer: The diamond problem arises when a class inherits the same method from two parents that share an ancestor, which makes it ambiguous which version to use. Java avoids it for classes by allowing only single inheritance. For interface default methods, the compiler forces the class to resolve the conflict explicitly.

interface Printer { default String name() { return "printer"; } }
interface Scanner { default String name() { return "scanner"; } }

class AllInOne implements Printer, Scanner {
    @Override public String name() {                       // required, or it's a compile error
        return Printer.super.name() + "+" + Scanner.super.name();
    }
}

Key points to cover:

  • The resolution rules:
    1. A method from a class beats an interface default.
    2. A more specific interface beats a less specific one.
    3. Otherwise, the class must override the method.

Q11. What's the difference between Comparable and Comparator?

Short answer: Comparable defines a class's natural ordering. The class itself implements compareTo, and there's exactly one such ordering. Comparator defines an external, custom ordering. You can have as many as you like, and you pass them to sorting methods.

record Employee(String name, int salary) implements Comparable<Employee> {
    public int compareTo(Employee o) { return name.compareTo(o.name); }      // natural order: by name
}
employees.sort(Comparator.comparingInt(Employee::salary).reversed()          // custom: salary desc,
                         .thenComparing(Employee::name));                    //         then by name

Key points to cover:

  • Collections.sort(list) and TreeSet use the natural order. Pass a Comparator for anything else.
  • Never compare with subtraction (return a.salary - b.salary;), because it overflows for large values. Use Integer.compare(a, b) or Comparator.comparingInt.
  • Keep compareTo consistent with equals. A TreeSet treats a compareTo result of 0 as a duplicate.

Learn it in depth → TreeMap & LinkedHashMap

Q12. What is encapsulation? Give an example.

Short answer: Encapsulation means bundling data with the methods that operate on it, and restricting direct access to that data. Fields are private, and the class exposes controlled operations that keep its state valid.

public class Wallet {
    private long balancePaise;                              // hidden state

    public void debit(long paise) {                         // controlled access keeps the invariant
        if (paise <= 0) throw new IllegalArgumentException("amount must be positive");
        if (paise > balancePaise) throw new IllegalStateException("insufficient balance");
        balancePaise -= paise;
    }
    public long balancePaise() { return balancePaise; }     // read-only view
}

Key points to cover:

  • The goal is to protect invariants: the balance can never go negative, whoever calls the class.

Learn it in depth → Classes and Objects

Q13. How does encapsulation improve security and integrity?

Short answer: Only the class's own methods can change its state, so every change goes through validation. Invalid states become impossible, misuse is limited, and the internal representation can change without breaking callers.

Key points to cover:

  • Defensive copies: return List.copyOf(items), or an unmodifiable view, instead of the internal list. Otherwise callers can modify your state behind your back.
  • Combining encapsulation with immutability (final fields, no setters) makes objects inherently thread safe.

Advertisement

Follow-up questions this topic invites — and their answers

Q: Can an abstract class implement an interface without implementing its methods? A: Yes. The abstract class can leave some or all interface methods unimplemented. The first concrete subclass must implement whatever is left.

Q: Can an interface extend a class? A: No. An interface can only extend other interfaces.

Q: Why were private methods added to interfaces in Java 9? A: So that several default methods can share helper code without exposing that helper as part of the public contract.

Q: Are abstraction and encapsulation the same thing? A: No, although they work together. Abstraction is about designing a simple outward view (what to expose). Encapsulation is about enforcing it: hiding and protecting the internals behind access control.

Advertisement

Previous

Polymorphism, Overloading & Overriding — Interview Questions

Next

Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions

AI Tutor

Lesson: Abstraction, Interfaces & Encapsulation — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.