Sub topic 3
Abstract Methods: Promises Without Bodies
In the last chapter you learned to mark a class as abstract. That keeps anyone from creating an object of it directly. An abstract class becomes much more useful once it holds abstract methods. This chapter covers what an abstract method is, how to write one, and which rules the Java compiler checks for you.
What Is an Abstract Method?
An abstract method is a method that has a name, parameters, and a return type, but no body. It is a promise. It says, "Every real object of this type will be able to do this. I just don't say how."
A method signature is the part of a method that says its name, its parameters, and its return type. An abstract method is a signature with the abstract keyword in front and a semicolon at the end. It has no curly braces.
abstract class Animal {
public abstract String sound();
}Compare it with a normal method, which is called a concrete method. A concrete method has a body:
class Dog {
public String sound() {
return "Woof";
}
}| Part | Abstract method | Concrete method |
|---|---|---|
| `abstract` keyword | Yes | No |
| Curly braces `{ }` | No | Yes |
| Ends with | A semicolon `;` | A closing brace `}` |
| Has code that runs | No | Yes |
Why Leave the Body Out?
Sometimes a parent class knows that something must happen but cannot know how. Every animal makes a sound, but there is no single "animal sound." A dog barks and a cat meows. If you wrote a body in Animal, you would have to make up a fake answer, such as returning an empty string. A fake answer hides bugs.
An abstract method lets you skip the fake answer. Each subclass then has to give the real one, and the compiler checks that it does.
A Complete Example
Here is a full program. The abstract class Animal has one abstract method, sound(), and one concrete method, speak(). Notice that speak() calls sound() even though Animal never says what sound() does.
abstract class Animal {
private final String name;
protected Animal(String name) {
this.name = name;
}
// The promise: every animal has a sound.
public abstract String sound();
// Concrete code that relies on the promise.
public void speak() {
System.out.println(name + " says " + sound());
}
}
class Dog extends Animal {
Dog() {
super("Dog");
}
@Override
public String sound() {
return "Woof";
}
}
class Cat extends Animal {
Cat() {
super("Cat");
}
@Override
public String sound() {
return "Meow";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
Animal b = new Cat();
a.speak(); // prints: Dog says Woof
b.speak(); // prints: Cat says Meow
}
}Save this as Main.java, then run javac Main.java and java Main. When speak() runs on a Dog, Java calls the Dog version of sound(). When it runs on a Cat, Java calls the Cat version. Because of the abstract method, Animal can write code that works for animals that don't exist yet.
The Rules the Compiler Enforces
Java checks abstract methods strictly. Each rule below comes with the kind of error you will see if you break it.
Rule 1: No body allowed
An abstract method can't have braces, not even empty ones.
abstract class Animal {
public abstract String sound() { } // error: abstract methods cannot have a body
}The reverse mistake is also an error. If you leave out the body and also forget the abstract keyword, the compiler reports "missing method body, or declare abstract".
Rule 2: Only abstract classes may hold abstract methods
If a class has even one abstract method, the class itself must be marked abstract.
class Animal { // error: Animal is not abstract and
public abstract String sound(); // does not override abstract method sound()
}This rule makes sense. If you could write new Animal(), then calling sound() on it would have no code to run.
Rule 3: A subclass must keep every promise or stay abstract
A subclass that extends an abstract class has two choices:
- Implement every abstract method, which makes it a concrete class you can use with
new. - Leave some abstract methods unimplemented and be declared
abstractitself.
If it does neither, you get an error such as "Fish is not abstract and does not override abstract method sound() in Animal".
Rule 4: Abstract methods cannot be private, static, or final
Each of these keywords blocks overriding in some way, so each one clashes with abstract:
| Combination | Why it fails |
|---|---|
| `private abstract` | Subclasses can't see a private method, so they can't override it. |
| `static abstract` | Static methods belong to the class, not to objects, so they are not overridden. |
| `final abstract` | `final` means "never override", but `abstract` means "you must override". |
You can use public, protected, or no access modifier at all on an abstract method.
Rule 5: The implementation can't be less visible
When you implement an abstract method, you can keep its access level or make it more open. You can't make it more closed. If sound() is public in Animal, then Dog must also declare it public. Writing protected String sound() in Dog is an error.
Edge Case: Keeping Promises in Steps
A long chain of classes can fill in abstract methods a few at a time. Only the class at the bottom has to be concrete.
abstract class Vehicle {
public abstract int wheels();
public abstract String fuel();
public String summary() {
return wheels() + " wheels, runs on " + fuel();
}
}
// Keeps one promise, leaves the other open, so it stays abstract.
abstract class Bike extends Vehicle {
@Override
public int wheels() {
return 2;
}
}
// Keeps the last promise, so it can be concrete.
class EBike extends Bike {
@Override
public String fuel() {
return "electricity";
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new EBike();
System.out.println(v.summary()); // prints: 2 wheels, runs on electricity
// Vehicle w = new Bike(); // compile error: Bike is abstract
}
}Bike gives the wheel count but says nothing about fuel, so it must stay abstract. EBike supplies the missing piece and becomes a class you can create objects from.
Common Beginner Mistakes
- Adding empty braces.
abstract void run() {}is an error. Use a semicolon:abstract void run();. - Forgetting to mark the class abstract. Add
abstractbeforeclass. - Missing one method in the subclass. The error message names the method you forgot. Implement it, or mark the subclass abstract.
- Changing the signature. Writing
sound(int volume)in the subclass creates a new method and doesn't implementsound().@Overridecatches this mistake.
Exercise
This code does not compile. Name both problems and fix them. class Shape { public abstract double area() { } }
Show answer
First, an abstract method can't have a body, so replace { } with a semicolon. Second, a class that contains an abstract method must be declared abstract. The fixed code is: abstract class Shape { public abstract double area(); }
Exercise
Abstract class Printer declares public abstract void print(); and public abstract void scan();. Class BasicPrinter extends Printer implements only print(). What must you do so the code compiles, and can you then write new BasicPrinter()?
Show answer
Either implement scan() in BasicPrinter, or declare BasicPrinter as abstract. If you implement scan(), BasicPrinter is concrete and new BasicPrinter() works. If you mark it abstract instead, it compiles, but new BasicPrinter() is an error.
Exercise
Why is private abstract void reset(); not allowed in Java?
Show answer
A private method can't be seen by subclasses, so no subclass could override it. An abstract method only makes sense if a subclass overrides it, so the two keywords contradict each other.