Abstract Classes
The Partial Blueprint.
Abstract Classes
Analogy: blueprint
An Abstract Class is like a Partial Blueprint.
It defines some things (like "All houses have walls"), but leaves other things undefined (like "What style is the roof?").
You cannot build a house from a partial blueprint. You must first complete it (Subclass it).
The Blueprint Builder
We have a House blueprint.
- It already has Walls and a Roof.
- But the Style is abstract.
You must choose a style to complete the class and build the house.
Blueprint Builder (Abstract Classes)
Abstract Class
- Walls (Implemented)
- Roof (Implemented)
- Style (Abstract!)
"I know I have walls and a roof, but I don't know what I look like yet!"
Implement Subclass:
?
Incomplete Blueprint. Cannot instantiate.
The Code
Use the abstract keyword.
Java Example
Switch language in Navbar
abstract class House {
// Implemented Method (Concrete)
void buildWalls() {
System.out.println("Building walls...");
}
// Abstract Method (No Body!)
abstract void designStyle();
}
// Concrete Subclass
class Castle extends House {
@Override
void designStyle() {
System.out.println("Adding towers and a moat!");
}
}
Up Next
Exception Handling