Sub topic 4
Writing a Concrete Subclass
An abstract class cannot be used on its own. You cannot write new with it. To get a real object, you need a concrete subclass. A concrete subclass is an ordinary class that extends an abstract class and provides a body for every abstract method it inherits.
This chapter shows how to write one, what the compiler checks, and the mistakes beginners make most often.
What "Concrete" Means
A concrete class is a class you can create objects from. It has no abstract methods left over. Every method it has, including the ones it inherits, has a body.
An abstract class works like a form with blank spaces. The concrete subclass fills in every blank. Once all the blanks are filled, Java lets you create objects of that class.
A First Example
Here is an abstract class Animal. It has one abstract method, sound(), and one regular method, speak().
abstract class Animal {
public abstract String sound();
public String speak() {
return "The animal says " + sound();
}
}
class Dog extends Animal {
@Override
public String sound() {
return "Woof";
}
}
class Cat extends Animal {
@Override
public String sound() {
return "Meow";
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
System.out.println(dog.speak()); // prints: The animal says Woof
System.out.println(cat.speak()); // prints: The animal says Meow
}
}Look at what each part does:
class Dog extends AnimalmakesDoga subclass ofAnimal.Dogwrites a body forsound(). That is the only blank it had to fill.Doggetsspeak()for free. It inherits that method fromAnimalwithout changing it.- When
speak()runs, it callssound(). Java uses theDogversion for a dog and theCatversion for a cat.
The Steps to Write a Concrete Subclass
- Write
class YourName extends TheAbstractClass. - Find every abstract method in the parent class, and in any abstract classes above it.
- For each one, write a method with the same name and the same parameter types.
- Put
@Overrideabove each of these methods. - If the parent has a constructor that takes arguments, call it with
super(...)as the first line of your constructor.
Why Use @Override?
@Override is an annotation, a label that tells the compiler something about your code. It says: "This method is meant to replace a method from the parent."
You can leave it out, but you should not. Suppose you misspell the method name:
class Cow extends Animal {
public String sond() { // typo: should be sound
return "Moo";
}
}Without @Override, the compiler sees sond() as a brand new method. sound() is still not implemented, so you get an error saying that Cow is not abstract and does not override sound(). With @Override on sond(), the compiler points straight at the typo: "method does not override or implement a method from a supertype." That message is much easier to understand.
What the Compiler Checks
The compiler enforces the promise the abstract class made. If you forget an abstract method, the code does not compile.
| Situation | Result |
|---|---|
| All abstract methods have bodies | Compiles. You can use `new` on the class. |
| One abstract method is missing | Compile error: the class is not abstract and does not override the method. |
| Method has a different parameter list | Counts as a new method. The abstract one is still missing. |
| Method is less visible, for example `protected` instead of `public` | Compile error: you cannot reduce visibility. |
| Method returns a different, unrelated type | Compile error: incompatible return type. |
Calling the Parent Constructor
Abstract classes can have constructors. You cannot call them with new, but a subclass can call them with super(...). The next chapter covers this in detail. For now, here is the basic rule.
abstract class Vehicle {
private final int wheels;
protected Vehicle(int wheels) {
this.wheels = wheels;
}
public int getWheels() {
return wheels;
}
public abstract String fuel();
}
class Bike extends Vehicle {
Bike() {
super(2);
}
@Override
public String fuel() {
return "legs";
}
}
public class Main {
public static void main(String[] args) {
Bike bike = new Bike();
System.out.println(bike.getWheels() + " wheels, runs on " + bike.fuel());
// prints: 2 wheels, runs on legs
}
}Vehicle has no constructor without parameters. So Bike must call super(2). If it does not, the compiler reports an error because it cannot find a matching constructor.
Edge Case: A Subclass That Stays Abstract
A subclass does not have to fill in every blank. It can fill in some of them and stay abstract itself. Then a class further down the line finishes the job.
abstract class Employee {
public abstract double monthlyPay();
public abstract String title();
}
abstract class SalariedEmployee extends Employee {
private final double yearlySalary;
protected SalariedEmployee(double yearlySalary) {
this.yearlySalary = yearlySalary;
}
@Override
public double monthlyPay() {
return yearlySalary / 12;
}
}
class Manager extends SalariedEmployee {
Manager() {
super(120000);
}
@Override
public String title() {
return "Manager";
}
}
public class Main {
public static void main(String[] args) {
Manager m = new Manager();
System.out.println(m.title() + " earns " + m.monthlyPay());
// prints: Manager earns 10000.0
}
}SalariedEmployee implements monthlyPay() but not title(). It must be marked abstract, or it will not compile. Manager implements the last missing method, title(), so it is concrete.
Edge Case: Overriding a Concrete Method Too
A concrete subclass may also replace the regular methods it inherits. For example, Dog could provide its own speak(). This is allowed but not required. Only abstract methods must be overridden.
If a parent method is marked final, no subclass can override it. You will see why that matters in the chapter on the template method pattern.
Common Mistakes
- Forgetting one abstract method, often one declared in a grandparent class.
- Leaving off
publicon the overriding method. - Changing the parameter types, which creates a new method instead of an override.
- Forgetting
super(...)when the parent has no constructor without parameters. - Trying
new Animal(). Only concrete subclasses can be created withnew.
Exercise
An abstract class Shape declares public abstract double area(); and public abstract double perimeter();. You write class Square extends Shape with only an area() method. What happens, and what are your two ways to fix it?
Show answer
The code does not compile, because Square is not abstract and does not override perimeter(). You can fix it by adding a public perimeter() method with @Override to Square, or by declaring Square abstract so that a later subclass implements perimeter().
Exercise
In a subclass of Animal you write @Override String sound() { return "Quack"; } with no access modifier. Why does this fail to compile?
Show answer
The abstract method sound() in Animal is public. With no modifier, the new method is package-private, which is less visible than public. Java does not allow an override to reduce visibility, so the method must be declared public.
Exercise
Write a concrete class Truck that extends the Vehicle class from this chapter. A truck has 6 wheels and runs on diesel.
Show answer
class Truck extends Vehicle { Truck() { super(6); } @Override public String fuel() { return "diesel"; } }. Calling new Truck().getWheels() returns 6, and fuel() returns "diesel".