Java Abstract Class — Summary
Definition
- A class declared with the
abstractkeyword. - Cannot be instantiated directly.
- Can contain abstract methods (no body) and concrete methods (with body).
Key Points
Purpose
- To provide a base class with common fields/methods while enforcing subclasses to implement certain methods.
Abstract Methods
- Declared without a body:
abstract void draw(); - Must be implemented by the first concrete subclass.
- Declared without a body:
Concrete Methods
- Abstract classes can also have fully implemented methods.
Constructors & Fields
- Can have constructors, instance variables, and static members.
Inheritance Rules
- A subclass must either:
- Implement all abstract methods, or
- Be declared abstract itself.
- Supports single inheritance (unlike interfaces which can be multiple).
- A subclass must either:
Difference from Interface
- Abstract class: can have state (fields), constructors, and both abstract & concrete methods.
- Interface: cannot have instance fields (only constants), but can have default/static methods (Java 8+).
Example
abstract class Shape {
String color;
// Abstract method
abstract double area();
// Concrete method
void setColor(String color) {
this.color = color;
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override double area() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(5);
s.setColor("Red");
System.out.println("Area: " + s.area());
}
}✅ When to use:
- You have a base class with shared code but also methods that must be implemented by subclasses.