Abstraction
Abstract classes, interfaces, and the difference between abstraction and encapsulation.
Definition
Abstraction hides implementation details and exposes only the essential features of an object. It focuses on what an object does rather than how it does it.
Abstract Classes
An abstract class cannot be instantiated directly. It can contain both abstract methods (no body) and concrete methods (with body).
abstract class Vehicle {
abstract void start(); // abstract — no implementation
void stop() { // concrete — has implementation
System.out.println("Vehicle stopped");
}
}
- Abstract classes can have constructors, fields, and concrete methods.
- A subclass must implement all abstract methods or be declared abstract itself.
Interfaces
An interface defines a contract — a set of methods that implementing classes must provide.
interface Flyable {
void fly(); // implicitly public and abstract
}
- A class can implement multiple interfaces (Java’s alternative to multiple inheritance).
- Since Java 8, interfaces can have
defaultandstaticmethods with implementations.
Abstraction vs. Encapsulation
| Aspect | Abstraction | Encapsulation |
|---|---|---|
| Focus | Hiding complexity | Hiding data |
| Mechanism | Abstract classes, interfaces | Access modifiers, getters/setters |
| Purpose | Design-level simplification | Implementation-level protection |
Example
// AbstractionDemo.java
// Demonstrates abstraction using abstract classes and interfaces in Java.
// Abstract class
abstract class Vehicle {
// Abstract method
abstract void start();
}
// Concrete subclass
class Car extends Vehicle {
void start() {
System.out.println("Car starts with key");
}
}
// Interface
interface Flyable {
void fly();
}
// Class implementing interface
class Plane implements Flyable {
public void fly() {
System.out.println("Plane is flying");
}
}
public class AbstractionDemo {
public static void main(String[] args) {
// Abstract class reference to subclass
Vehicle v = new Car();
v.start();
// Interface reference to implementing class
Flyable f = new Plane();
f.fly();
}
}
Full source:
examples/11-abstraction/AbstractionDemo.java