Notes › OOP
Abstract Class vs Interface
Both are tools for abstraction: they define what subclasses must do without (fully) saying how. Neither can be instantiated with new.
Abstract class
A class marked abstract that can mix abstract methods (no body) and normal methods (with a body), and can have state (fields) and constructors.
abstract class Shape {
protected String color; // state
Shape(String color) { this.color = color; } // constructor (called via super)
abstract double area(); // must be implemented by children
void describe() { // shared, concrete behaviour
System.out.printf("%s shape with area %.2f%n", color, area());
}
}
class Circle extends Shape {
private final double r;
Circle(String color, double r) { super(color); this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
private final double w, h;
Rectangle(String color, double w, double h) { super(color); this.w = w; this.h = h; }
@Override double area() { return w * h; }
}
Shape s = new Circle("red", 2); // ✅ reference of the abstract type
s.describe(); // red shape with area 12.57
// new Shape("blue"); // ❌ cannot instantiate
- A class with any abstract method must be abstract.
- An abstract class may have zero abstract methods (just to stop direct instantiation).
- A child must implement all abstract methods or be abstract itself.
- This is the Template Method pattern:
describe()is fixed,area()varies.
Interface
A contract — a list of capabilities a class promises to provide. A class can implement many interfaces.
interface Payable {
double FEE = 0.02; // implicitly public static final (a constant)
void pay(double amount); // implicitly public abstract
default void receipt(double amount) { // Java 8+: has a body
System.out.println("Paid " + amount * (1 + FEE));
}
static boolean valid(double amount) { // Java 8+: called as Payable.valid(x)
return amount > 0;
}
}
interface Refundable { void refund(String txnId); }
class UpiPayment implements Payable, Refundable { // multiple interfaces ✅
public void pay(double amount) { System.out.println("UPI " + amount); }
public void refund(String txnId) { System.out.println("Refund " + txnId); }
}
Interface evolution in Java:
| Version | Interfaces could have |
|---|---|
| Java 7 | abstract methods + constants only |
| Java 8 | + default and static methods |
| Java 9 | + private methods (helpers for default methods) |
Default methods let library authors add methods to an interface without breaking every class that implements it (e.g. List.sort, Collection.stream).
If two interfaces give the same default method, the class must override it and can pick one: A.super.hello().
Functional interfaces
An interface with exactly one abstract method — can be implemented with a lambda.
@FunctionalInterface
interface Discount { double apply(double price); }
Discount festive = p -> p * 0.8;
System.out.println(festive.apply(500)); // 400.0
Built-in ones: Runnable, Comparator<T>, Function<T,R>, Predicate<T>, Supplier<T>, Consumer<T>.
Marker interfaces
No methods at all — just tag a class: Serializable, Cloneable. (Annotations are the modern alternative.)
The comparison
| Abstract class | Interface | |
|---|---|---|
| Keyword | abstract class, extends |
interface, implements |
| Methods | abstract + concrete | abstract + default + static + private |
| Fields | any (instance, static, final or not) | only public static final constants |
| Constructors | yes | no |
| Access modifiers on methods | any | public (private helpers since Java 9) |
| Multiple inheritance | a class extends one | a class implements many |
| State | can hold state | no instance state |
| Relationship | IS-A (Circle is a Shape) | CAN-DO (UpiPayment can be paid, refunded) |
| Speed of adding methods | add a concrete method freely | add a default method |
When to use which
Choose an abstract class when:
- Related classes share code and state (fields, constructors).
- You want to provide a partly built base (template method).
- You need non-public members.
Choose an interface when:
- Unrelated classes should share a capability (
Comparable,Runnable,Payable). - You need multiple inheritance of type.
- You're defining an API/contract for others to implement — great for dependency injection and testing with mocks.
Common combination: an interface for the contract, an abstract class that partly implements it, concrete classes on top — e.g. List → AbstractList → ArrayList.
In C++ and Python
C++ has no interface keyword — a class with only pure virtual functions acts as one:
class Shape {
public:
virtual double area() const = 0; // pure virtual → Shape is abstract
virtual ~Shape() = default; // always a virtual destructor
};
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() const override { return 3.14159 * r * r; }
};
Python uses the abc module:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
class Square(Shape):
def __init__(self, s): self.s = s
def area(self): return self.s ** 2
# Shape() → TypeError: Can't instantiate abstract class
Python also relies on duck typing and typing.Protocol for interface-like checks.
Interview one-liners
- Abstract class = partial implementation with state; interface = pure contract (plus default methods).
- A class can extend one abstract class but implement many interfaces.
- Interface fields are always
public static final. - Abstract classes can have constructors; interfaces cannot.
- IS-A → abstract class; CAN-DO → interface.
- Related: Four Pillars of OOP, SOLID Principles, Java 8 Features.