Java Abstraction
Abstraction hides complex implementation details and exposes only the essential features of an object. In Java, abstraction is achieved using abstract classes and interfaces.
An abstract class can have both abstract methods (no body, to be implemented by subclasses) and concrete methods, and cannot be instantiated directly.
abstract class C {
abstract void method();
}Abstract classes
Declared with the `abstract` keyword, abstract classes can contain abstract methods (declared but not implemented) as well as regular methods with implementations.
Why use abstraction?
Abstraction lets you define a common contract for related classes while letting each subclass provide its own specific implementation details.
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
double radius = 2;
double area() { return Math.PI * radius * radius; }
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle();
System.out.println(s.area());
}
}12.566370614359172Shape defines the abstract area() method, and Circle provides its concrete implementation.
Key points
- Abstract classes cannot be instantiated directly.
- Abstract methods have no body; subclasses must implement them.
- Abstract classes can mix abstract and concrete methods.
- Abstraction defines a contract while hiding implementation details.
