In the Abstraction chapter we saw that a good design shows what an object can do and hides how it does it. Object-oriented languages give us two main tools for writing down that "what": abstract classes and interfaces.
Both let you declare methods without writing their bodies, both cannot be instantiated directly, and both are used with polymorphism. So students (and interviewers) keep asking the same question: "If they look so similar, why do we need both, and when do I pick which one?"
This chapter answers that question carefully. Our main language is Java (where the difference is clearest), with short C++ and Python comparisons at the end.
An abstract class is a partially built class: it can hold state, constructors and finished methods, and leaves some methods for its subclasses to complete. An interface is a contract: a set of capabilities a class promises to provide, without saying anything about how the class stores its data.
A useful one-line intuition: an abstract class answers "what is this thing?" (a FullTime employee is an Employee), while an interface answers "what can this thing do?" (an Order can be paid, can be tracked).
Abstract Classes: A Partially Built Class
An abstract class is declared with the abstract keyword. It may contain:
abstract methods (no body), which every concrete subclass must implement,
concrete methods (with a body), which subclasses inherit for free,
fields of any kind (instance or static, final or not),
constructors, which run when a subclass object is created.
Let us model a payroll system. Every employee has a name and a base salary, and every employee prints a payslip in the same format. Only the rule for computing the monthly pay differs. That is the perfect shape for an abstract class: lots of shared code and state, one "hole" for subclasses to fill.
abstract class Employee {
private final String name; // state lives here
protected final double baseSalary;
Employee(String name, double baseSalary) { // abstract classes have constructors
this.name = name;
this.baseSalary = baseSalary;
System.out.println("Employee constructor for " + name);
}
abstract double monthlyPay(); // each subclass decides HOW
void printPayslip() { // shared, concrete behaviour
System.out.printf("%-6s : Rs. %.2f%n", name, monthlyPay());
}
}
class FullTime extends Employee {
FullTime(String name, double baseSalary) { super(name, baseSalary); }
@Override
double monthlyPay() { return baseSalary + 0.20 * baseSalary; } // + 20% HRA
}
class Intern extends Employee {
Intern(String name, double stipend) { super(name, stipend); }
@Override
double monthlyPay() { return baseSalary; }
}
public class PayrollDemo {
public static void main(String[] args) {
Employee[] staff = { new FullTime("Asha", 50000), new Intern("Ravi", 15000) };
for (Employee e : staff) e.printPayslip();
// Employee e = new Employee("X", 1); // error: Employee is abstract; cannot be instantiated
}
}Output:
Employee constructor for Asha
Employee constructor for Ravi
Asha : Rs. 60000.00
Ravi : Rs. 15000.00Walk through what happened:
new FullTime("Asha", 50000)callssuper(name, baseSalary), so the abstract class's constructor runs and initialises the shared fields. An abstract class cannot be instantiated on its own, but its constructor is still very much used.printPayslip()is written once inEmployee. Inside it, the callmonthlyPay()is dynamically dispatched toFullTimeorIntern.The subclasses wrote only the part that is actually different.
If you try to create an Employee directly, the compiler stops you:
abstract class Employee { abstract double monthlyPay(); }
public class Bad { public static void main(String[] a) { Employee e = new Employee(); } } Bad.java:2: error: Employee is abstract; cannot be instantiated
public class Bad { public static void main(String[] a) { Employee e = new Employee(); } }
^
1 errorRules worth remembering
If a class has even one abstract method, the class must be declared
abstract.The reverse is not required: a class can be
abstractwith zero abstract methods. This is done when the class exists only to be extended and creating it directly makes no sense.A subclass that does not implement all inherited abstract methods must itself be declared
abstract.An abstract method cannot be
private,staticorfinal, because each of those would prevent a subclass from overriding it.A class can
extendonly one class, abstract or not.
Interfaces: A Contract of Capabilities
An interface lists methods that implementing classes promise to provide. Modern Java interfaces (Java 8 and later) can contain more than just abstract methods:
Member in an interface | Since | Implicit modifiers / notes |
|---|---|---|
Abstract method | Java 1.0 |
|
Constant field | Java 1.0 |
|
| Java 8 |
|
| Java 8 | called as |
| Java 9 | helper for default/static methods; invisible outside the interface |
What an interface still cannot have: instance fields (per-object state) and constructors. That is the deep difference, and we will come back to it.
Here is an interface with every kind of member, and a class that implements two interfaces at once:
interface Payable {
double GST_RATE = 0.18; // implicitly public static final
double amount(); // implicitly public abstract
default String receipt() { // Java 8+: default method
return "Paid Rs. " + format(amount() * (1 + GST_RATE));
}
static Payable of(double value) { // Java 8+: static method
return () -> value; // Payable has one abstract method, so a lambda works
}
private String format(double x) { // Java 9+: private helper
return String.format("%.2f", x);
}
}
interface Trackable {
String trackingId();
}
class Order implements Payable, Trackable { // one class, two interfaces
private final double price;
private final String id;
Order(String id, double price) { this.id = id; this.price = price; }
@Override public double amount() { return price; }
@Override public String trackingId() { return id; }
}
public class InterfaceDemo {
public static void main(String[] args) {
Order o = new Order("ORD-42", 1000);
System.out.println(o.trackingId() + " -> " + o.receipt());
Payable p = o; // same object seen through two "views"
Trackable t = o;
System.out.println(p.amount() + " " + t.trackingId());
Payable tip = Payable.of(50);
System.out.println(tip.receipt());
System.out.println(Payable.GST_RATE);
}
}Output:
ORD-42 -> Paid Rs. 1180.00
1000.0 ORD-42
Paid Rs. 59.00
0.18Points to notice:
Orderwrote onlyamount()andtrackingId(). It gotreceipt()for free from the default method.The implementing methods are
public. Interface methods are implicitly public, and an implementation cannot reduce visibility.One object,
o, can be referred to as aPayableor as aTrackable. Code that only needs payment does not need to know anything about tracking.Payablehas exactly one abstract method, so it is a functional interface and a lambda() -> valuecan implement it. Abstract classes can never be implemented by a lambda.
Multiple Inheritance and the Diamond Problem
Java allows a class to extend one class but implement many interfaces. Why the difference?
As we saw in Types of Inheritance, the classic danger of multiple inheritance is the diamond problem: if two parents both provide state or a method with the same signature, which one does the child get? With classes, the trouble is mostly about state (two copies of the same fields, two constructors to run). Interfaces have no instance state and no constructors, so most of that danger disappears.
Default methods brought back one small piece of the problem: two interfaces may both supply a default body for the same method. Java resolves it with three simple rules:
Classes win. A method inherited from a superclass (declared or inherited there) beats any interface default.
More specific interface wins. If interface
BextendsAand both define the default,B's version is used.Otherwise, you must choose. The class must override the method; inside it, it can call a particular parent with
InterfaceName.super.method().
interface Camera {
default String describe() { return "I can take photos"; }
}
interface MusicPlayer {
default String describe() { return "I can play music"; }
}
class SmartPhone implements Camera, MusicPlayer {
// Without this override: compile error, two defaults clash
@Override
public String describe() {
return Camera.super.describe() + " and " + MusicPlayer.super.describe();
}
}
class Device {
public String describe() { return "I am a device"; }
}
class Tablet extends Device implements Camera {
// no override needed: the superclass method wins over the interface default
}
public class DiamondDemo {
public static void main(String[] args) {
System.out.println(new SmartPhone().describe());
System.out.println(new Tablet().describe());
}
}Output:
I can take photos and I can play music
I am a deviceIf SmartPhone did not override describe(), the code would not compile:
Clash.java:3: error: types Camera and MusicPlayer are incompatible;
class SmartPhone implements Camera, MusicPlayer { }
^
class SmartPhone inherits unrelated defaults for describe() from types Camera and MusicPlayer
1 error Camera MusicPlayer
describe() {...} describe() {...}
\ /
\ /
SmartPhone → must override describe()
and may call Camera.super.describe()Side-by-Side Comparison (Java)
Feature | Abstract class | Interface |
|---|---|---|
Keyword to use it |
|
|
How many per class | Only one | Any number |
Instance fields (state) | Yes, any kind | No; only |
Constructors | Yes (called via | No |
Methods with a body | Yes, any number | Only |
Access modifiers on members | Any ( | Methods are |
| Yes | No |
Implemented by a lambda | Never | Yes, if it is a functional interface |
Relationship expressed | "is-a" with shared implementation | "can-do" capability |
Adding a new method later | Add a concrete method: subclasses unaffected | Add a |
The row that matters most in practice is state. Default methods let interfaces carry behaviour, but they still cannot carry per-object data. A default method can only work by calling other interface methods, like receipt() calling amount().
When to Use Which
Prefer an interface when
You are describing a capability that unrelated classes may share:
Comparable,Runnable,AutoCloseable,Payable. AStringand aLocalDateare unrelated classes with no useful common parent, yet both areComparable.A class may need several such roles at once.
You want callers to depend on a small, stable contract rather than a concrete class (this keeps classes loosely coupled, as we will see in Coupling & Cohesion).
You want to allow lambdas (functional interfaces).
Prefer an abstract class when
Closely related classes share state and code, like our
EmployeewithnameandprintPayslip().You need constructors to enforce that every subclass starts in a valid state.
You need
protectedor package-private helpers, orfinalmethods that subclasses must not change (a "template" method that fixes the order of steps).
Using both together
Large libraries often use both: an interface for the contract and an abstract class that implements the boring parts of it. The Java Collections Framework does exactly this: List is an interface, and AbstractList is an abstract class that implements most of List on top of just get() and size(). ArrayList extends AbstractList, and your code declares variables of type List.
List (interface: the contract)
▲
│ implements
AbstractList (abstract class: shared code)
▲
│ extends
ArrayList (concrete class)The Same Ideas in C++ and Python
C++: pure virtual functions
C++ has no interface or abstract keyword. A class becomes abstract when it has at least one pure virtual function (declared with = 0). A class whose members are only pure virtual functions (plus a virtual destructor) plays the role of an interface. Because C++ allows multiple inheritance of classes, a class can inherit from several such "interfaces" and from an abstract class at the same time.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <numbers>
#include <vector>
// "Interface": only pure virtual functions + virtual destructor
class Drawable {
public:
virtual void draw() const = 0;
virtual ~Drawable() = default;
};
// Abstract class: has state and a pure virtual function
class Shape {
protected:
std::string name;
public:
explicit Shape(std::string n) : name(std::move(n)) {}
virtual double area() const = 0; // pure virtual -> Shape is abstract
void report() const { std::cout << name << " area = " << area() << '\n'; }
virtual ~Shape() = default;
};
// C++ allows inheriting from several classes, abstract or not
class Circle : public Shape, public Drawable {
double r;
public:
explicit Circle(double r) : Shape("Circle"), r(r) {}
double area() const override { return std::numbers::pi * r * r; }
void draw() const override { std::cout << "Drawing a circle of radius " << r << '\n'; }
};
int main() {
// Shape s("x"); // error: cannot declare variable 's' to be of abstract type 'Shape'
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2.0));
for (const auto& s : shapes) s->report();
Circle c(1.0);
const Drawable& d = c;
d.draw();
}Output:
Circle area = 12.5664
Drawing a circle of radius 1Two C++ details students often miss:
Give an abstract base class a virtual destructor. Deleting a derived object through a base pointer without one is undefined behaviour.
A pure virtual function may still have a definition (written outside the class). The class stays abstract; derived classes can call the base version explicitly.
Python: the abc module
Python has no interface keyword either. You inherit from ABC and mark methods with @abstractmethod. The check happens at run time, when you try to create the object.
from abc import ABC, abstractmethod
import math
class Shape(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def area(self):
...
def report(self):
print(f"{self.name} area = {self.area():.2f}")
class Circle(Shape):
def __init__(self, r):
super().__init__("Circle")
self.r = r
def area(self):
return math.pi * self.r ** 2
Circle(2).report()
try:
Shape("x")
except TypeError as e:
print("TypeError:", e)Output:
Circle area = 12.57
TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'Python also supports structural typing through typing.Protocol: a class satisfies a protocol simply by having the right methods, without inheriting from it. That is closer to how interfaces feel in Go than in Java.
Concept | Java | C++ | Python |
|---|---|---|---|
Abstract method |
|
|
|
Interface |
| Class with only pure virtual functions |
|
Multiple inheritance of classes | No | Yes | Yes |
Instantiation error caught at | Compile time | Compile time | Run time ( |
Common Mistakes
"Interfaces cannot have method bodies." Out of date since Java 8. They can have
default,staticand (since Java 9)privatemethods. They still cannot have instance fields or constructors."Abstract classes have no constructors." They do, and they run every time a subclass object is created.
"An abstract class must have an abstract method." Not in Java. It may have none.
Forgetting
publicwhen implementing an interface method. Writingdouble amount()withoutpublicgives "attempting to assign weaker access privileges".Trying to keep state in an interface. A field like
int count = 0;in an interface is astatic finalconstant shared by everyone, not a per-object counter.Calling a static interface method on the implementing class.
Order.of(5)does not compile; static interface methods are called only asPayable.of(5).Using an abstract class only to force method names. If there is no shared state or code, an interface is the lighter, more flexible choice.
Interview and GATE-Style Questions
Q1. Can an abstract class have a constructor? If it cannot be instantiated, why would it need one?
Yes. The constructor initialises the fields declared in the abstract class. It runs as part of creating a subclass object, through the subclass constructor's super(...) call (explicit or implicit).
Q2. After Java 8 added default methods, is there any difference left between an abstract class and an interface?
Yes, several: an interface cannot have instance fields or constructors, its non-private methods are always public, it cannot have final or protected methods, and a class can implement many interfaces but extend only one class. Default methods give interfaces behaviour, not state.
Q3. A class implements two interfaces that both have default void show(). What happens?
default void show(). What happens?Compilation fails ("inherits unrelated defaults") unless the class overrides show(). Inside the override it may call A.super.show() and/or B.super.show(). If the class's superclass already has a show(), that one wins and no override is needed.
Q4. Which of these compile? (a) abstract final class X {} (b) abstract class Y {} with no abstract methods (c) an interface with a constructor (d) a private method in an interface
abstract final class X {} (b) abstract class Y {} with no abstract methods (c) an interface with a constructor (d) a private method in an interface(a) No: abstract needs subclassing and final forbids it. (b) Yes. (c) No: interfaces never have constructors. (d) Yes, since Java 9.
Q5. In C++, how do you make a class abstract, and what else should it always have?
Declare at least one pure virtual function, for example virtual double area() const = 0;. It should also have a virtual destructor so that deleting through a base pointer destroys the derived object correctly.
Q6. You are designing Bird, Airplane and Drone. All can fly, but they share no code. Abstract class or interface for flying?
Bird, Airplane and Drone. All can fly, but they share no code. Abstract class or interface for flying?An interface such as Flyable. The three classes are unrelated (no common "is-a" parent), share no state, and a Bird may already extend an Animal class, so it needs flying as an extra capability.
Summary
Abstract class: a partially built class. Can have state, constructors, concrete and abstract methods, any access level. Single inheritance.
Interface: a contract of capabilities. Abstract,
default,staticandprivatemethods plus constants; no instance state, no constructors. A class can implement many.Default-method conflicts: class wins, then the more specific interface, otherwise override and pick with
X.super.m().Choose an abstract class for related types sharing code and data; choose an interface for capabilities shared across unrelated types. Often use both: interface for the contract, abstract class as a helper implementation.
C++ uses pure virtual functions (and multiple inheritance); Python uses
ABCand@abstractmethod, checked at run time.
Abstract class: "what you are, plus some of what you do." Interface: "what you promise you can do."