I. What Are Abstract Classes and Interfaces
In object-oriented programming, abstract classes and interfaces are both important abstraction mechanisms.
Their common goal is: define a set of specifications so that different concrete types provide behavior according to a unified contract.
However, their design purposes are not exactly the same.
- Abstract Class: used to define the common foundation of a class of objects and can contain properties, constructors, regular methods, and abstract methods.
- Interface: used to define the behavioral contract that a type must follow, describing which capabilities a type should have.
For example, a payment system may include Alipay, WeChat Pay, and bank card payment.
These payment methods all need to implement payment behavior, but the specific payment logic differs.
A unified payment specification can be defined through an abstract class or interface, and then concrete types provide the implementation.
flowchart TB
A["Payment System"]
B["Abstract Definition"]
C["Concrete Payment Implementations"]
D["Alipay"]
E["WeChat Pay"]
F["Bank Card Payment"]
A --> B
B --> C
C --> D
C --> E
C --> F
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
II. Abstract Classes
2.1 Definition of Abstract Classes
An abstract class is a class that cannot be instantiated directly and is usually used as a common base class for other classes.
An abstract class can contain:
| Member Type | Allowed | Description |
|---|---|---|
| Regular properties | Usually allowed | Store the state of an object or type |
| Regular methods | Allowed | Provide reusable common implementations |
| Abstract methods | Allowed | Declare behavior that concrete subclasses must implement |
| Constructors | Allowed | Initialize base class state |
| Static members | Depends on the language | Provide class-level data or behavior |
| Constants | Depends on the language | Define fixed values |
An abstract class can take on two responsibilities at the same time:
- Define the behavioral specification that subclasses must follow.
- Provide common state and reusable implementations for subclasses.
2.2 Abstract Methods
An abstract method only declares a behavioral requirement and does not provide a complete concrete implementation; concrete subclasses are required to implement it according to the contract.
Java example:
abstract class Animal {
public abstract void speak();
public void sleep() {
System.out.println("Animal is sleeping");
}
}
Here:
speak()is an abstract method.sleep()is a regular method.Animalis an abstract class and cannot be instantiated directly vianew Animal().
Concrete subclass:
class Dog extends Animal {
@Override
public void speak() {
System.out.println("汪汪");
}
}
Create an object:
Animal animal = new Dog();
animal.speak();
animal.sleep();
Dog implements the abstract method and also inherits the common implementation of sleep().
Note that different languages have different requirements for defining and implementing abstract methods. For example, Python uses the abc module to provide an abstract base class mechanism, while C++ uses pure virtual functions to express abstract behavior.
2.3 Abstract Classes Cannot Be Instantiated Directly
An abstract class itself is usually an incomplete type definition.
For example:
abstract class Shape {
abstract double area();
}
The following code will not compile:
Shape shape = new Shape();
The reason is that Shape only declares the area calculation behavior and does not provide a complete implementation.
This can be done through a concrete subclass:
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
Invocation:
Shape shape = new Circle(5);
System.out.println(shape.area());
Here the declared variable type is Shape, while the actual object type is Circle.
This is also an important way in which abstract classes support runtime polymorphism.
2.4 Main Uses of Abstract Classes
Abstract classes are suitable for the following scenarios:
- Multiple subclasses share the same basic state.
- Multiple subclasses need to share a common implementation.
- Subclasses must implement certain specific behaviors.
- You want to manage initialization and common workflows uniformly through a base class.
- A clear parent-child type relationship needs to be established.
For example, a base file processor can provide common reading, closing, and exception-handling logic while requiring different file types to implement their specific parsing methods.
III. Interfaces (Interface)
3.1 Definition of an Interface
An interface is a type abstraction used to define a behavioral contract.
It usually describes which operations a type should have, without requiring those types to share the same internal data structure or implementation.
For example:
Runnable: indicates the ability to execute a task.Comparable: indicates that objects can be compared.Serializable: indicates support for serialization.Payment: indicates payment capability.
Interfaces emphasize capability rather than which specific category an object belongs to.
3.2 Basic Structure of an Interface
Java example:
interface Payment {
void pay(double amount);
void refund(double amount);
}
This interface defines two behaviors:
- Payment.
- Refund.
Concrete implementation classes need to provide corresponding implementations:
class Alipay implements Payment {
@Override
public void pay(double amount) {
System.out.println("支付宝支付:" + amount);
}
@Override
public void refund(double amount) {
System.out.println("支付宝退款:" + amount);
}
}
Another implementation:
class WechatPay implements Payment {
@Override
public void pay(double amount) {
System.out.println("微信支付:" + amount);
}
@Override
public void refund(double amount) {
System.out.println("微信退款:" + amount);
}
}
The two classes do not need to inherit from the same concrete payment parent class; they can still provide a unified capability by implementing the same interface.
3.3 A Class Can Implement Multiple Interfaces
This is an important feature of interfaces compared with the traditional single-inheritance class hierarchy.
Java example:
interface Runnable {
void run();
}
interface Swimmable {
void swim();
}
class Robot implements Runnable, Swimmable {
@Override
public void run() {
System.out.println("机器人正在移动");
}
@Override
public void swim() {
System.out.println("机器人正在游泳");
}
}
Robot has both running and swimming capabilities.
This approach allows different capabilities to be split into separate interfaces and then combined according to the needs of a specific type.
flowchart TB
A["Robot"]
B["Runnable interface"]
C["Swimmable interface"]
D["run()"]
E["swim()"]
A --> B
A --> C
B --> D
C --> E
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3.4 Interfaces Can Contain More Than Abstract Methods
Early Java interfaces were mainly used to define abstract methods and constants.
Starting with Java 8, interfaces also support:
- Default methods.
- Static methods.
Java 9 added support for private methods.
For example:
interface Payment {
void pay(double amount);
default void validate(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("支付金额必须大于零");
}
}
static boolean isValidAmount(double amount) {
return amount > 0;
}
private void log(String message) {
System.out.println(message);
}
}
Different types of interface members have different semantics:
| Member | Role |
|---|---|
| Abstract method | Defines behavior that implementing classes must provide |
| Default method | Provides an inheritable default implementation for implementing classes |
| Static method | Provides operations that belong to the interface itself |
| Private method | Supports reuse among methods inside the interface |
| Constant | Defines fixed values at the interface level |
Note that fields in Java interfaces are public static final by default and cannot serve as instance fields stored independently for each implementing object.
3.5 Interfaces and Structural Typing
Interfaces are not the only mechanism for abstraction in every language.
Different languages have different type abstraction mechanisms:
- Java and C# use explicit interface implementation.
- Go uses implicit interface implementation.
- TypeScript uses structural type checking.
- Rust uses traits to define shared behavior constraints.
- Python can express interface-like constraints through mechanisms such as abstract base classes and protocols (Protocol).
For example, in Go:
package main
import "fmt"
type Speaker interface {
Speak()
}
type Dog struct{}
func (Dog) Speak() {
fmt.Println("汪汪")
}
type Cat struct{}
func (Cat) Speak() {
fmt.Println("喵喵")
}
func MakeSound(s Speaker) {
s.Speak()
}
func main() {
MakeSound(Dog{})
MakeSound(Cat{})
}
In Go, Dog and Cat do not need to explicitly declare that they implement Speaker.
As long as a type's method set satisfies the interface requirements, it can be considered to implement that interface.
This reflects Go's implicit interface mechanism.
4. Core Differences Between Abstract Classes and Interfaces
Both abstract classes and interfaces can define abstract behavior, but their design focus is different.
4.1 Core Comparison
| Comparison dimension | Abstract class | Interface |
|---|---|---|
| Primary purpose | Define a common base and partial implementation | Define a behavioral contract |
| Instantiation | Usually cannot be instantiated directly | Cannot directly create interface instances |
| Regular attributes | Usually supported | Depends on the language; Java interfaces do not support instance fields |
| Constructors | Usually supported | Java interfaces do not support constructors |
| Regular methods | Supported | Depends on the language; supports default implementations, etc. |
| Abstract methods | Supported | Usually supported |
| State management | Can store instance state | Usually not responsible for instance state management |
| Inheritance count | In Java, C#, etc., a class can usually inherit only one class | Multiple interfaces can usually be implemented |
| Relationship expression | is-a | has-a capability / can-do |
| Typical use | Common base implementation | Cross-type capability abstraction |
Note: This table mainly uses languages such as Java that have a traditional abstract class and interface system as reference. Interface capabilities are not entirely the same across different languages.
4.2 Differences in Design Intent
Abstract classes usually express:
These types belong to the same category of things and share a common foundational structure.
For example:
- Dog is a kind of Animal.
- Circle is a kind of Shape.
- AdminUser is a kind of User.
Interfaces usually express:
These types all possess a certain capability.
For example:
- Printer can print.
- File can be read.
- Payment can make payments.
- Comparable can be compared.
A single class can belong to one base type while implementing multiple capability interfaces.
flowchart TB
A["Concrete type"]
B["Abstract class<br/>Common base"]
C["Interface A<br/>Capability constraint"]
D["Interface B<br/>Capability constraint"]
E["Concrete implementation"]
A --> B
A --> C
A --> D
B --> E
C --> E
D --> E
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
V. Underlying Implementation Mechanisms of Abstract Classes and Interfaces
Understanding the two cannot stop at the syntax level; it is also necessary to understand how compilers and runtimes handle these abstract definitions.
5.1 Implementation Mechanism of Abstract Classes
Taking Java as an example, abstract classes generate bytecode after compilation.
Abstract methods have an abstract method flag in bytecode and do not contain the executable instructions corresponding to a regular method body.
Concrete subclasses need to provide implementations that meet the requirements.
At runtime, the JVM executes the corresponding method based on the object's actual type.
Note the following:
- An abstract class is still a class itself.
- An abstract class can have instance fields.
- An abstract class can have constructors.
- An abstract class can provide already implemented methods.
- An abstract class cannot be instantiated directly, but its construction logic can be executed during subclass creation.
For example:
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void speak();
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void speak() {
System.out.println(name + " 汪汪");
}
}
When a Dog object is created, the parent class construction logic participates in the object initialization process.
5.2 Implementation Mechanism of Interfaces
Taking Java as an example, interfaces are also a kind of type in the JVM type system.
Interfaces define method contracts, and implementing classes need to satisfy the corresponding implementation requirements.
Interface calls can be completed through the JVM's interface method dispatch mechanism.
At the bytecode level, there are instructions related to interface calls, such as invokeinterface.
Common call instructions also include:
| Instruction | Main purpose |
|---|---|
invokevirtual |
Call instance virtual methods |
invokeinterface |
Call interface methods |
invokestatic |
Call static methods |
invokespecial |
Call constructors, private methods, or a specific superclass implementation |
These are mechanisms at the JVM bytecode level; they do not mean that interface calls in every language work the same way.
5.3 Do abstract classes and interfaces incur runtime overhead?
Abstract classes and interfaces are themselves type abstraction mechanisms, and one should not simply assume that they are bound to add significant runtime overhead.
What really deserves attention is the concrete implementation and the way calls are made.
For example:
- Virtual method calls may involve dynamic dispatch.
- Interface calls may require interface method lookup.
- The JIT compiler may optimize calls through type analysis.
- When the runtime type can be determined, the compiler may perform devirtualization.
- Generics in some languages may use monomorphization, reducing runtime dispatch.
In Java, an interface call is not necessarily slower than an abstract class method call. Actual performance depends on the runtime type distribution, JIT optimization, call frequency, and the specific code structure.
One should not abandon sound abstraction design merely to avoid interface call overhead.
Six. How abstract classes and interfaces are implemented in mainstream languages
6.1 Java
Java supports both abstract classes and interfaces.
abstract class Animal {
public abstract void speak();
public void eat() {
System.out.println("Eating");
}
}
interface Runnable {
void run();
}
class Dog extends Animal implements Runnable {
@Override
public void speak() {
System.out.println("汪汪");
}
@Override
public void run() {
System.out.println("Dog running");
}
}
Java's type relationships:
- A class can directly inherit from only one class.
- A class can implement multiple interfaces.
- An interface can extend multiple interfaces.
- An abstract class can implement interfaces, and can also extend other abstract classes.
- A concrete class must implement all abstract methods not yet implemented in its inheritance hierarchy.
6.2 C++
C++ has no separate interface keyword.
Interfaces are usually simulated with abstract classes that contain only pure virtual functions.
#include <iostream>
class Payment {
public:
virtual void pay(double amount) = 0;
virtual ~Payment() = default;
};
class Alipay : public Payment {
public:
void pay(double amount) override {
std::cout << "支付宝支付:" << amount << std::endl;
}
};
int main() {
Payment* payment = new Alipay();
payment->pay(100);
delete payment;
}
Here:
virtual void pay(double amount) = 0;
denotes a pure virtual function.
A class that contains at least one pure virtual function and has not completed its implementation is an abstract class and cannot be instantiated directly.
In C++, an interface is usually a design convention rather than a separate language type category.
6.3 Python
Python implements constraints similar to abstract classes and interfaces through abstract base classes (Abstract Base Class, ABC).
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass
def validate(self, amount):
return amount > 0
class Alipay(Payment):
def pay(self, amount):
if not self.validate(amount):
raise ValueError("金额必须大于零")
print(f"支付宝支付:{amount}")
Here:
ABCprovides the abstract base class mechanism.@abstractmethoddeclares an abstract method.- A subclass must implement all abstract methods not yet implemented before it can be instantiated normally.
validate()is an ordinary method that can be reused.
Python also supports Protocol, which is used to describe structural interfaces.
from typing import Protocol
class Payment(Protocol):
def pay(self, amount: float) -> None:
...
class Alipay:
def pay(self, amount: float) -> None:
print(f"支付宝支付:{amount}")
def process(payment: Payment):
payment.pay(100)