Abstraction is a core concept of object-oriented programming in Java. It focuses on exposing the behavior that other parts of a program need while hiding implementation details that do not need to be known by the caller.
For example, when you call a method such as
car.start(), you usually care that the car starts.
You do not need to know every internal operation involved in the engine, fuel system,
sensors, or electrical components. The method provides a simple interface while the
implementation remains behind that interface.
Java primarily provides two mechanisms for creating abstractions: abstract classes and interfaces. They overlap in some capabilities, but they are designed for different kinds of relationships.
What Is Abstraction?
Abstraction means defining the important capabilities of a type without requiring every caller to understand its implementation. It helps separate what an object can do from how the object does it.
Application
|
v
Payment
|
+----------------+
| |
v v
CardPayment UpiPayment
| |
v v
Card API UPI API
The application can depend on the common payment abstraction without needing every caller to know the details of card or UPI processing.
Why Use Abstraction?
Simplifies Complexity
Callers work with a small set of meaningful operations instead of internal implementation details.
Reduces Coupling
Code can depend on abstractions instead of being tied directly to one implementation.
Supports Polymorphism
Different implementations can be used through the same parent type or interface.
Improves Maintainability
Internal implementations can change while callers continue using the same abstraction.
Abstract Classes
An abstract class is a class declared
using the abstract keyword.
It is designed to serve as a base class for related types and cannot be instantiated directly.
abstract class Vehicle {
abstract void startEngine();
}
You cannot create an object directly from an abstract class:
// Not allowed
Vehicle vehicle = new Vehicle();
Instead, a concrete subclass extends the abstract class and provides implementations for the required abstract methods.
Abstract Methods
An abstract method declares a method without providing an implementation. A concrete subclass must implement the abstract method unless the subclass is itself abstract.
abstract class Vehicle {
public abstract void startEngine();
}
class Car extends Vehicle {
@Override
public void startEngine() {
System.out.println("Car engine started");
}
}
The parent class defines what behavior every concrete Vehicle must provide, while Car defines how that behavior works for a specific vehicle.
Abstract Classes Can Have Concrete Methods
An abstract class is not limited to abstract methods. It can also contain ordinary concrete methods with implementations. These methods can provide shared behavior to subclasses and can be overridden when the subclass needs specialized behavior.
abstract class Vehicle {
public abstract void startEngine();
public void stopEngine() {
System.out.println("Engine stopped");
}
}
class Car extends Vehicle {
@Override
public void startEngine() {
System.out.println("Car engine started");
}
}
Here, startEngine() must be supplied by the subclass,
while stopEngine() already provides shared behavior.
In Java, concrete instance methods are dynamically dispatched when overridden.
Java does not use a virtual keyword like some other
object-oriented languages; ordinary non-static instance methods already participate
in dynamic dispatch unless restricted by the language rules.
Abstract Classes Can Have Fields
Abstract classes can contain instance fields and static fields. This makes them useful when related subclasses share state or initialization logic.
abstract class Vehicle {
protected String name;
protected Vehicle(String name) {
this.name = name;
}
public abstract void startEngine();
}
class Car extends Vehicle {
public Car(String name) {
super(name);
}
@Override
public void startEngine() {
System.out.println(name + " engine started");
}
}
The superclass owns the shared name state,
while the subclass supplies its specific engine behavior.
Constructors in Abstract Classes
Abstract classes can define constructors even though they cannot be instantiated directly. These constructors run as part of constructing a concrete subclass object.
abstract class Animal {
protected String name;
protected Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
}
The super(name) call initializes the part of the
object defined by the Animal class.
Abstract Class Example
A useful abstract class defines shared behavior and leaves specialized behavior to concrete subclasses.
abstract class Payment {
protected String transactionId;
protected Payment(String transactionId) {
this.transactionId = transactionId;
}
public abstract void pay(double amount);
public void printReceipt() {
System.out.println(
"Receipt: " + transactionId
);
}
}
class CardPayment extends Payment {
public CardPayment(String transactionId) {
super(transactionId);
}
@Override
public void pay(double amount) {
System.out.println(
"Paid " + amount + " using card"
);
}
}
Payment defines the shared contract and state, while CardPayment supplies the implementation of the payment operation.
Interfaces
An interface defines a contract that implementing classes agree to follow. Interfaces are useful when several classes should provide a common capability without necessarily sharing the same class hierarchy or state implementation.
interface PaymentMethod {
void pay(double amount);
}
A class implements an interface with the
implements keyword:
class CardPayment implements PaymentMethod {
@Override
public void pay(double amount) {
System.out.println("Paid using card");
}
}
Interfaces Are More Than Method Declarations
Modern Java interfaces can contain more than abstract method declarations. They can contain abstract methods, default methods, static methods, and private methods used by interface implementations of shared behavior.
interface Logger {
void log(String message);
default void logInfo(String message) {
log("INFO: " + message);
}
static String format(String message) {
return "[LOG] " + message;
}
private String normalize(String message) {
return message.trim();
}
}
The exact interface design should match the responsibility of the abstraction. Default methods can provide shared behavior, while static methods belong to the interface itself.
Interface Fields
Variables declared in an interface are implicitly
public,
static, and
final.
They therefore represent constants rather than per-object mutable instance state.
interface ApplicationConfig {
int MAX_RETRIES = 3;
}
public class Main {
public static void main(String[] args) {
System.out.println(
ApplicationConfig.MAX_RETRIES
);
}
}
Unlike an abstract class, an interface is not used to hold ordinary per-instance mutable fields for implementing objects.
Implementing Multiple Interfaces
A Java class can implement multiple interfaces. This provides a flexible way for one class to satisfy several independent contracts.
interface Printable {
void print();
}
interface Shareable {
void share();
}
class Document implements Printable, Shareable {
@Override
public void print() {
System.out.println("Printing document");
}
@Override
public void share() {
System.out.println("Sharing document");
}
}
This is one of the major differences between class inheritance and interfaces: a class can extend one class but can implement multiple interfaces.
Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Can be instantiated directly? | No | No |
| Abstract methods | Yes | Yes |
| Concrete methods | Yes | Yes, through supported default and other method forms |
| Instance fields | Yes | No |
| Constructors | Yes | No |
| Class inheritance | Subclass extends one class | Class can implement multiple interfaces |
| Typical role | Shared base implementation and state | Capability or contract |
When Should You Use an Abstract Class?
An abstract class is a good fit when several related classes share meaningful implementation or state in addition to sharing a conceptual base type.
- Related subclasses share common state.
- Several subclasses need the same implementation for part of their behavior.
- The base class constructor needs to establish common state.
- The relationship naturally represents an "is-a" hierarchy.
- You need protected or private implementation details shared through the hierarchy.
When Should You Use an Interface?
An interface is often appropriate when the important idea is a capability or contract that different and potentially unrelated classes should provide.
- Different classes should provide the same capability.
- You want multiple types to implement the same contract.
- The implementation should remain independent of a specific class hierarchy.
- You want callers to depend on behavior rather than a concrete implementation.
- You are designing an API or extension point for multiple implementations.
Programming Against an Interface
One of the most useful applications of abstraction is declaring variables and method parameters using an interface instead of a concrete implementation.
interface NotificationSender {
void send(String message);
}
class EmailSender implements NotificationSender {
@Override
public void send(String message) {
System.out.println("Email: " + message);
}
}
class SmsSender implements NotificationSender {
@Override
public void send(String message) {
System.out.println("SMS: " + message);
}
}
public class NotificationService {
public static void sendNotification(
NotificationSender sender,
String message
) {
sender.send(message);
}
}
The service does not need to know whether the sender uses email, SMS, or another implementation. It only depends on the NotificationSender contract.
Default Methods in Interfaces
A default method allows an interface to provide an implementation that implementing classes can inherit or override.
interface Vehicle {
void start();
default void stop() {
System.out.println("Vehicle stopped");
}
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
car.start();
car.stop();
}
}
A class can override the default method when its behavior needs to differ.
Resolving Default Method Conflicts
A class can inherit default methods from multiple interfaces. If two interfaces provide conflicting defaults with the same method signature, the implementing class must resolve the conflict.
interface A {
default void show() {
System.out.println("A");
}
}
interface B {
default void show() {
System.out.println("B");
}
}
class C implements A, B {
@Override
public void show() {
A.super.show();
}
}
The implementing class explicitly chooses the behavior it wants. This keeps the multiple-interface design deterministic.
Abstraction and Polymorphism
Abstraction and polymorphism work naturally together. A variable can use an abstract type while the actual object provides the concrete implementation.
interface Shape {
double area();
}
class Circle implements Shape {
private final double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
Shape shape = new Circle(5);
System.out.println(shape.area());
The caller depends on Shape rather than Circle.
A different implementation of Shape could be substituted without changing code that
only needs to call area().
Abstract Classes and Interfaces Together
A Java class can extend an abstract class and implement one or more interfaces. This allows shared implementation and multiple capabilities to be combined.
interface Chargeable {
void charge();
}
abstract class Device {
protected String name;
protected Device(String name) {
this.name = name;
}
public abstract void powerOn();
}
class Laptop extends Device implements Chargeable {
public Laptop(String name) {
super(name);
}
@Override
public void powerOn() {
System.out.println(name + " powered on");
}
@Override
public void charge() {
System.out.println(name + " charging");
}
}
Device provides shared base behavior and state, while Chargeable describes an additional capability that the Laptop supports.
A Practical Payment Abstraction
Payment systems are a useful example because applications often need to support several payment implementations while keeping business logic independent of the underlying payment provider.
interface PaymentMethod {
void pay(double amount);
}
class CardPayment implements PaymentMethod {
@Override
public void pay(double amount) {
System.out.println(
"Processing card payment: " + amount
);
}
}
class UpiPayment implements PaymentMethod {
@Override
public void pay(double amount) {
System.out.println(
"Processing UPI payment: " + amount
);
}
}
class PaymentService {
public void process(
PaymentMethod paymentMethod,
double amount
) {
paymentMethod.pay(amount);
}
}
public class Main {
public static void main(String[] args) {
PaymentService service =
new PaymentService();
service.process(
new CardPayment(),
1500
);
service.process(
new UpiPayment(),
800
);
}
}
PaymentService depends on the PaymentMethod abstraction.
It does not need separate methods such as
processCardPayment() and
processUpiPayment().
New payment implementations can follow the same contract.
Common Abstraction Mistakes
Treating Interfaces as Only "Method Signature Lists"
Modern Java interfaces can also contain default, static, and private methods. Design the interface around the contract and behavior it should expose.
Thinking Abstract Classes Cannot Have Implementation
Abstract classes can contain fields, constructors, concrete methods, and abstract methods.
Using Abstract Classes for Unrelated Concepts
An abstract class represents a base type in an inheritance hierarchy. It should not be introduced simply to share arbitrary utility code.
Creating Extremely Large Interfaces
An interface with many unrelated responsibilities forces implementations to depend on behavior they may not actually need.
Depending Directly on Concrete Implementations
When interchangeable implementations are expected, depending on an interface can reduce coupling and make substitution easier.
Using Abstraction Without a Real Need
Not every small class needs an interface or abstract base class. Introduce abstractions when they solve a genuine design or variability problem.
Choosing Between an Abstract Class and Interface
Ask what the abstraction represents.
- If related classes need shared state, constructors, and common implementation, an abstract class may be a natural fit.
- If several potentially unrelated classes need to support a common capability or contract, an interface is often a better fit.
- If the primary relationship is "is-a", inheritance may be appropriate.
- If the primary relationship is "can-do", an interface can often express the design clearly.
Abstraction in a Real Application
In production applications, abstraction is often used at boundaries between parts of a system. For example, an application may define a repository interface while providing different implementations for a database, an in-memory test environment, or another data source.
Application Service
|
v
UserRepository
|
+----+----+
| |
v v
Database InMemory
Repository Repository
The service depends on the repository contract instead of knowing how users are stored. This separation can make the application easier to test and modify.
Abstraction Design Checklist
- Does the abstraction represent a meaningful concept or capability?
- Are the exposed methods focused on what callers actually need?
- Should related classes share state or implementation?
- Would multiple unrelated classes benefit from the same contract?
- Can callers depend on the abstraction without knowing implementation details?
- Is the abstraction small enough to remain understandable?
- Are concrete implementation details kept outside the public contract?
Abstraction Flow
Abstraction
|
+----------+----------+
| |
v v
Abstract Class Interface
| |
v v
Shared State & Contract /
Implementation Capability
| |
+----------+----------+
|
v
Concrete Classes
|
v
Runtime Objects
The abstraction defines what the rest of the application can rely on, while concrete classes provide the actual behavior.
Java Abstraction: Key Takeaways
- Abstraction hides unnecessary implementation details behind a useful API.
- Abstract classes cannot be instantiated directly.
- Abstract classes can contain abstract methods and concrete methods.
- Abstract classes can contain fields and constructors.
- Subclasses must implement inherited abstract methods unless they remain abstract.
- Interfaces define contracts and can be implemented by multiple classes.
- Interfaces can contain abstract, default, static, and private methods.
- Interface fields are implicitly public, static, and final.
- A class can extend one class and implement multiple interfaces.
- Abstraction works naturally with polymorphism.
- Abstract classes are useful when related types share state or implementation.
- Interfaces are useful for independent capabilities and common contracts.
- Good abstractions expose useful behavior rather than unnecessary implementation details.
Summary
Java abstraction allows developers to separate the interface of a component from the details of its implementation. Abstract classes are useful when related classes share state, constructors, and implementation, while interfaces are useful when multiple classes need to follow a common contract or capability.
Abstract classes can contain both abstract and concrete methods, fields, and constructors. Interfaces can define contracts and, in modern Java, can also provide default, static, and private methods. A class can extend one parent class while implementing multiple interfaces.
The most valuable use of abstraction is reducing unnecessary coupling. When application code depends on a meaningful abstraction instead of a specific implementation, different implementations can be replaced or extended without changing the code that consumes them.