Abstract Classes
1. What Is Abstract? (beginner)
Abstract class = half-built blueprint (has SOME ready methods + SOME empty promises!). Can't new it (incomplete!) — child MUST fill promises (or stay abstract!). Like flat floor-plan: walls promised, paint your choice!
2. Code — Shape Area (exam classic!)
abstract class Shape { // abstract (no new Shape()!)
String color;
Shape(String c) { color = c; } // ctor OK! (child via super!)
void show() { System.out.println("color=" + color); } // concrete (ready!)
abstract double area(); // PROMISE (no body! child MUST write!)
}
class Circle extends Shape {
double r;
Circle(double r) { super("red"); this.r = r; }
@Override double area() { return Math.PI * r * r; } // fulfilled!
}
// Shape s = new Shape("x"); // ERROR! (abstract — incomplete!)
// Shape s = new Circle(7); s.area(); // 153.94 (polymorphism!)
3. Rules (exam traps!)
abstractmethod: NO body (;only!), in abstract class only!- Child must implement ALL abstracts (else child abstract too!).
- Abstract CAN have ctor, fields, concrete methods, static, main!
abstract+finaltogether = ERROR (final bans child, abstract needs child!).
4. Abstract vs Interface (preview!)
| Abstract class | Interface | |
|---|---|---|
new? |
No | No |
| Methods | mix (ready + abstract) | all abstract (Java 7) / default ok (8+) |
| Extends | one parent | many interfaces! |
5. Exam Points
- Shape program + rules — 7 marks, very frequent.
- Abstract vs interface +
finalclash — 5 marks, frequent.