Sub topic 12
Control Inheritance with abstract and final
Inheritance lets one class (a subclass) reuse and change the code of another class (a superclass). Sometimes a designer wants to limit that reuse. Java gives you two keywords for this: abstract and final.
abstractmeans "this is incomplete." You cannot create an object from it directly.finalmeans "this cannot be changed by a subclass."
Abstract Classes and Methods
An abstract class is a class marked with the word abstract. It works like a template. An abstract method is a method with no body. Each concrete (complete) subclass must write its own version of it.
abstract class Shape {
abstract double area();
String describe() {
return "A shape with area " + area();
}
}
class Square extends Shape {
private final double side;
Square(double side) {
this.side = side;
}
@Override
double area() {
return side * side;
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Square(3);
System.out.println(s.describe());
}
}The program prints A shape with area 9.0. The method describe() lives in Shape, but it calls area(). Java runs the Square version, because the object is a Square.
> Note: new Shape() will not compile. The compiler says that Shape is abstract and cannot be instantiated.
Final Classes and Methods
A final class cannot be extended. A final method cannot be overridden.
final class Coin {
int value() {
return 25;
}
}
// class Dime extends Coin { } // Compile error: cannot inherit from final Coin
class Ticket {
final String code() {
return "T-100";
}
}
// class VipTicket extends Ticket {
// String code() { return "VIP"; } // Compile error: cannot override final method
// }Use final when a behavior must stay the same in every subclass. A security check is one example.
Quick Reference
| Keyword | Applies to | Effect |
|---|---|---|
| abstract | class | Cannot be created with `new`; may contain abstract methods |
| abstract | method | Has no body; each concrete subclass must write it |
| final | class | Cannot be extended |
| final | method | Cannot be overridden |
Common Mistakes
- Forgetting an abstract method. A concrete subclass that does not write every abstract method will not compile.
- Confusing final with a constant. On a variable,
finalmeans "assign once." On a class or method, it means "no inheritance" or "no overriding." - Overusing final. Each
finallimits future programmers. Use it when there is a clear reason.
Exercise
The class Ticket has a final method code(). Can VipTicket, a subclass of Ticket, define its own code() method with a different return value? Explain why or why not.
Show answer
No. A final method cannot be overridden, so the compiler reports an error. VipTicket can add a differently named method, such as vipCode(), instead.