Autocoder

Abstraction and Encapsulation Interview Questions

Last updated 2026-11-19

Abstraction and encapsulation are the two pillars candidates most often mix up. The sharp answer is that abstraction decides what to expose, while encapsulation protects what lies behind it. This page tests that distinction with code: where private fields still leak, how to build an immutable class, and how an abstract type separates callers from implementations.

It follows OOPs interview questions and complements inheritance and polymorphism. Design-heavy rounds continue in low-level design questions, and the plan for these rounds is in how to crack an OOPs interview.

Core contrastAbstraction hides complexity; encapsulation hides state
Code inJava, Python, C++
LevelEasy to medium

Where encapsulation quietly breaks

One example reused through the page

A PaymentGateway abstraction has one method, charge(amount, token). Callers see only that. RazorpayGateway and a fake in-memory gateway for tests implement it. Each implementation keeps its HTTP client, retry state and API keys private. That is abstraction at the type level and encapsulation inside each class.

Abstraction and Encapsulation Interview Questions: questions with worked answers

  1. 1

    What is the difference between abstraction and encapsulation?

    easy

    Abstraction is about design: showing only the essential operations and hiding implementation detail, so a caller uses start() on a Car without knowing how the engine works. It is achieved with abstract classes and interfaces. Encapsulation is about protection: bundling data with the methods that operate on it and restricting direct access with access modifiers, so the object can enforce its own rules. Abstraction answers "what can I do?", encapsulation answers "who may touch the data?".

  2. 2

    What is data hiding?

    easy

    Data hiding means making fields private so they can only be changed through the class's methods. That lets the class validate input, keep related fields consistent and change its internal representation later without breaking callers. For a BankAccount, balance is private, and withdraw() checks that it never goes negative. Data hiding is the mechanism, encapsulation is the broader idea of grouping data and behaviour.

    java
    class BankAccount {
        private long balance;                       // paise, hidden
        void deposit(long amt) {
            if (amt <= 0) throw new IllegalArgumentException("amount must be positive");
            balance += amt;
        }
        void withdraw(long amt) {
            if (amt > balance) throw new IllegalStateException("insufficient funds");
            balance -= amt;
        }
        long balance() { return balance; }
    }
  3. 3

    Are getters and setters always good encapsulation?

    medium

    No. A class with a private field and a public getter and setter for it offers no protection beyond syntax; callers can still put the object in any state. Good encapsulation exposes behaviour, such as account.transfer(to, amt), rather than raw data, an idea summarised as tell, don't ask. Offer setters only when mutation is a real operation, validate inside them, and prefer immutability where possible.

  4. 4

    How do you make a Java class immutable?

    medium

    Declare the class final so it cannot be subclassed, make all fields private and final, provide no setters, initialise everything in the constructor, and defensively copy mutable inputs and outputs. Immutable objects are thread-safe without locking, safe as map keys and easy to reason about. String is the standard example. The common bug is storing a caller's mutable Date or List directly.

    java
    public final class Booking {
        private final String id;
        private final List<String> seats;
        public Booking(String id, List<String> seats) {
            this.id = id;
            this.seats = List.copyOf(seats);       // defensive copy, unmodifiable
        }
        public String id() { return id; }
        public List<String> seats() { return seats; }   // already unmodifiable
    }
  5. 5

    This class has private fields. Show how encapsulation still leaks.

    medium

    If getItems() returns the internal ArrayList, a caller can call getItems().clear() or add elements, bypassing any validation in addItem(). The same happens when the constructor keeps a reference to the list passed in. Fix by returning an unmodifiable view or a copy, and copying on input. Private only controls the name, not who holds a reference to the object behind it.

    java
    class Cart {
        private final List<String> items = new ArrayList<>();
        void addItem(String s) { if (!s.isBlank()) items.add(s); }
        List<String> getItems() { return items; }                          // leaks
        List<String> getItemsSafe() { return Collections.unmodifiableList(items); }
    }
  6. 6

    How is abstraction achieved in Java and C++?

    easy

    In Java with abstract classes and interfaces: an abstract class may mix implemented and abstract methods, while an interface declares a contract. In C++ an abstract class has at least one pure virtual function, written virtual void draw() = 0, and cannot be instantiated; a class with only pure virtual functions acts as an interface. Python offers abc.ABC with @abstractmethod, which prevents instantiating a class that has unimplemented abstract methods.

    python
    from abc import ABC, abstractmethod
    class PaymentGateway(ABC):
        @abstractmethod
        def charge(self, amount_paise: int, token: str) -> str: ...
    class FakeGateway(PaymentGateway):
        def charge(self, amount_paise, token): return "txn-1"
    # PaymentGateway() raises TypeError; FakeGateway().charge(100, "t") works
  7. 7

    Can an abstract class have a constructor? Can you instantiate it?

    medium

    Yes, an abstract class can have constructors, and they run when a concrete subclass is created, to initialise the shared state. You cannot instantiate it directly with new. An anonymous subclass or a concrete subclass can be instantiated instead. An interface has no constructor because it holds no instance state.

  8. 8

    What can interfaces contain in Java 8 and later?

    medium

    Abstract methods, constant fields that are implicitly public static final, default methods with a body, static methods and, since Java 9, private methods for sharing code between defaults. Default methods let library authors add behaviour without breaking existing implementers. There is still no instance state, and if two interfaces supply conflicting defaults, the implementing class must override and choose.

  9. 9

    Design a PaymentGateway abstraction and explain the trade-offs.

    hard

    Define interface PaymentGateway with charge(request) returning a result object, then RazorpayGateway and FakeGateway implementations. Checkout depends on the interface and receives an implementation through its constructor, so tests inject the fake and no network is needed. Trade-offs: a very thin interface keeps callers simple but cannot expose provider-specific features such as UPI intents; a fat interface leaks one provider's model. Keep the interface to what your domain needs, put provider quirks inside adapters, and return domain errors instead of provider exceptions so the abstraction does not leak.

  10. 10

    How does Python implement encapsulation, given it has no private keyword?

    medium

    By convention and light mechanisms. A single underscore, _balance, signals "internal". A double underscore, __balance, triggers name mangling to _ClassName__balance, which avoids accidental clashes in subclasses but can still be accessed. The @property decorator exposes a validated attribute with attribute syntax, letting you start with a plain attribute and add validation later without changing callers.

    python
    class Account:
        def __init__(self): self._balance = 0
        @property
        def balance(self): return self._balance
        def deposit(self, amt):
            if amt <= 0: raise ValueError("positive only")
            self._balance += amt
  11. 11

    Difference between abstraction and information hiding?

    medium

    Information hiding is the design principle of concealing decisions likely to change behind a stable boundary, so other code does not depend on them. Abstraction is the act of defining that boundary as a simplified model. Encapsulation, with access modifiers, is one tool that enforces it. They overlap, and interviewers accept a clear short answer: abstraction chooses the interface, information hiding keeps the rest unreachable.

  12. 12

    What is a leaky abstraction?

    medium

    An abstraction that forces callers to know about the implementation behind it. An ORM that hides SQL still produces slow queries when you load a collection inside a loop, so users must understand the generated queries. A file API that pretends a network drive is local hides timeouts. Reduce leaks by documenting guarantees and failure modes, and by designing interfaces around what callers need, not how the implementation works.

Frequently asked questions

Can we achieve abstraction without abstract classes?

Yes. Interfaces, or simply a well-chosen public API on a concrete class with private internals, provide abstraction.

Is encapsulation possible without data hiding?

Bundling data and methods in a class is encapsulation in the structural sense, but without hiding the data, you lose its main benefit of enforced invariants.

Which is better for abstraction, abstract class or interface?

Prefer an interface for contracts across unrelated types, and an abstract class when subclasses share state or common code.

Why make fields private?

So the class can validate changes, keep invariants and change representation later without breaking code that uses it.

Related guides

More in CS Fundamentals Interview Questions

See all in this section