Sub topic 12
Control Inheritance with abstract and final
Inheritance lets a subclass reuse and change the behavior of a superclass. Sometimes you want to limit that. A class may be too incomplete to use on its own. A method may be too important to change. Java gives you two keywords for these cases: abstract and final.
This chapter assumes you know how to write classes, fields, methods, and constructors. It also assumes you know how extends, overriding, and super work.
What You Will Learn
- What an abstract class is, and why you cannot create an object from it
- How to declare abstract methods and implement them in subclasses
- How to use
finalon methods, classes, and variables - How to choose between
abstractandfinalfor a design
Abstract Classes
An abstract class is a class that is marked abstract. It is meant to be a base for other classes. You cannot create an object from it with new.
Why would you want that? Think about a Shape class. You can draw a circle or a square. But what is a plain "shape"? There is no such thing in the real world. A Shape class is useful as a common parent, but an object of type Shape alone makes no sense.
abstract class Shape {
private final String name;
Shape(String name) {
this.name = name;
}
String getName() {
return name;
}
}If you try this, the compiler stops you:
Shape s = new Shape("thing"); // compile error: Shape is abstractAn abstract class can still have fields, constructors, and normal methods. Its constructor runs when a subclass object is created, because the subclass constructor calls super(...). You learned this in the constructor chaining chapter.
Abstract Methods
An abstract method is a method with no body. It has a signature and a semicolon, and the keyword abstract. It says: "Every real subclass must provide this method."
abstract double area();Rules to remember:
- An abstract method has no braces and no body.
- A class with an abstract method must itself be declared
abstract. - A subclass that is not abstract must implement every inherited abstract method.
- An abstract class may have zero abstract methods. This is allowed, and it is a way to stop others from creating objects of the class.
A Complete Example
This program defines an abstract Shape with one abstract method, then two concrete subclasses.
abstract class Shape {
private final String name;
Shape(String name) {
this.name = name;
}
abstract double area();
String describe() {
return name + " with area " + area();
}
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
super("Circle");
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
class Square extends Shape {
private final double side;
Square(double side) {
super("Square");
this.side = side;
}
@Override
double area() {
return side * side;
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(1.0), new Square(2.0) };
for (Shape shape : shapes) {
System.out.println(shape.describe());
}
}
}The output is:
Circle with area 3.141592653589793
Square with area 4.0Look at describe() in Shape. It calls area(), but Shape does not know how to compute it. At run time, Java uses dynamic dispatch and picks Circle.area() or Square.area(). The abstract class sets the steps. The subclasses fill in the missing part.
You can still use Shape as a variable type. The array above holds Shape references that point to real Circle and Square objects. You just cannot write new Shape(...).
What if a subclass skips the method?
If a subclass does not implement every abstract method, the subclass must also be marked abstract. Otherwise the compiler reports an error.
class Triangle extends Shape { // compile error: does not implement area()
Triangle() {
super("Triangle");
}
}This is useful. The compiler checks your design for you. You cannot forget a required method.
Things abstract cannot be combined with
Some modifier combinations make no sense, and the compiler rejects them.
| Combination | Why it fails |
|---|---|
| `abstract` and `private` method | A private method cannot be seen by a subclass, so it can never be implemented. |
| `abstract` and `final` method | `final` forbids overriding, but `abstract` requires it. |
| `abstract` and `static` method | A static method is not overridden, so it cannot be abstract. |
| `abstract` and `final` class | A final class cannot be extended, so no one could implement the methods. |
The final Keyword
final means "this cannot be changed." Java uses it in three places. Two of them matter for inheritance.
Final methods
A final method cannot be overridden by a subclass.
class Account {
private double balance;
final void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
balance += amount;
}
double getBalance() {
return balance;
}
}
class SavingsAccount extends Account {
// void deposit(double amount) { } // compile error: cannot override final method
}Use a final method when the exact behavior must stay the same in every subclass. In the example, every account must check that the amount is positive. A subclass cannot skip that check.
Subclasses still inherit a final method and can call it. They just cannot replace it.
Final classes
A final class cannot be extended at all.
final class Money {
private final long cents;
Money(long cents) {
this.cents = cents;
}
long getCents() {
return cents;
}
}
// class BigMoney extends Money { } // compile error: cannot inherit from final MoneyYou have already used a final class. String is final. No one can write class MyString extends String. This guarantees that a String always behaves the way the language says it does.
All methods of a final class behave as if they were final, since no subclass can exist to override them.
Final variables
A final variable can be assigned only once. This is not about inheritance, but you see it in the examples above (private final String name).
final int limit = 10;
limit = 20; // compile error: cannot assign a value to final variableA final field must get its value either where it is declared or in every constructor. For a final reference, the reference cannot change, but the object it points to may still change its own contents.
final StringBuilder sb = new StringBuilder("hi");
sb.append("!"); // allowed: the object changes
// sb = new StringBuilder(); // compile error: the reference cannot changeAbstract and Final Compared
The two keywords pull in opposite directions.
| Row | `abstract` | `final` |
|---|---|---|
| On a class | Must be extended to be used | Cannot be extended |
| On a method | Must be overridden | Cannot be overridden |
| Can be combined? | No, not on the same class or method | No |
| Main idea | "Subclasses must finish this." | "Nobody may change this." |
A Pattern That Uses Both
A common design uses both keywords together. A template method is a final method in an abstract class. It fixes the order of steps, and subclasses supply the individual steps.
abstract class Report {
final void print() {
System.out.println(header());
System.out.println(body());
System.out.println("-- end --");
}
String header() {
return "Report";
}
abstract String body();
}
class SalesReport extends Report {
@Override
String body() {
return "Sales went up.";
}
}
public class Main {
public static void main(String[] args) {
new SalesReport().print();
}
}The output is:
Report
Sales went up.
-- end --print() is final, so the order never changes. body() is abstract, so every report must provide it. header() is a normal method, so a subclass may override it if it wants a different title.
Common Mistakes
- Creating an abstract class with
new. You can only create objects of concrete subclasses. You can, however, writeShape s = new Circle(1.0);. - Forgetting to implement an abstract method. The compiler tells you which class is missing which method.
- Making a class final too early. A final class blocks all reuse through inheritance, including in tests. Make a class final when you have a clear reason, such as safety or an unchanging value type.
- Thinking
finalon a reference makes the object unchangeable. It only fixes which object the variable points to. - Calling an overridable method from a constructor. A superclass constructor runs before the subclass fields are set. If it calls a method that a subclass overrides, that method may see default values such as
0ornull. Making the methodfinalavoids this problem.
Summary
- An abstract class cannot be instantiated. It can have fields, constructors, and ordinary methods.
- An abstract method has no body. Every concrete subclass must implement it.
- A final method cannot be overridden. A final class cannot be extended.
abstractandfinalcannot be applied together to the same class or method.- Abstract classes and final methods combine well in the template method pattern.
Exercise
A class Vehicle is declared abstract and has the abstract method abstract int wheels();. You write class Bike extends Vehicle { } with an empty body. Does it compile? What are two ways to fix it?
Show answer
It does not compile, because Bike is concrete but does not implement the inherited abstract method wheels(). Fix 1: add @Override int wheels() { return 2; } to Bike. Fix 2: declare Bike as abstract, which leaves the work to its own subclasses.
Exercise
Why does this code fail to compile? final abstract class Tool { }
Show answer
final means the class cannot be extended, and abstract means the class exists only to be extended. The two modifiers contradict each other, so the compiler rejects the combination.
Exercise
In the Report example, a teammate adds void print() { System.out.println("custom"); } to a subclass of Report. What happens, and why is this useful?
Show answer
The compiler reports an error because print() is final in Report and cannot be overridden. This guarantees that every report prints its header, body, and footer in the same order.