Sub topic 3
Abstract Methods: Promises Without Bodies
An abstract class can hold methods that have no code inside them. These are called abstract methods. This chapter shows how to write one and what Java requires once you do.
What Is an Abstract Method?
An abstract method is a method that has a name, parameters, and a return type, but no body. A method body is the code between the curly braces { }.
An abstract method is a promise. It says "every object of this type can do this," and it leaves the details to someone else.
Here is the syntax:
public abstract double area();There are two things to notice:
- The keyword
abstractcomes before the return type. - The line ends with a semicolon
;where the curly braces would normally go.
Why Leave Out the Body?
Some actions only make sense for a specific kind of thing. Every animal makes a sound, but a general "animal" has no single sound. A dog barks and a cat meows. The abstract method names the action, and each subclass fills it in. A subclass is a class that extends another class.
A Worked Example
abstract class Animal {
public abstract String makeSound();
public void speak() {
System.out.println("The animal says: " + makeSound());
}
}
class Dog extends Animal {
@Override
public String makeSound() {
return "Woof";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.speak(); // prints: The animal says: Woof
}
}The speak method calls makeSound() even though Animal never says what the sound is. This still works because any real object must come from a class like Dog, and Dog supplies the body.
The Rules
Java checks these rules when it compiles your code:
| Rule | What happens if you break it |
|---|---|
| A class with an abstract method must be declared `abstract` | Compile error |
| An abstract method has no body, only `;` | Compile error |
| A non-abstract subclass must override every abstract method | Compile error |
| An abstract method cannot be `private`, `static`, or `final` | Compile error |
The last rule makes sense once you think about it. A private method cannot be seen by subclasses, a static method cannot be overridden, and a final method is not allowed to be overridden. Each of these would stop a subclass from keeping the promise.
Exercises
Exercise
Why does this code fail to compile? class Shape { public abstract double area(); }
Show answer
Shape has an abstract method but is not declared abstract. Change it to abstract class Shape.
Exercise
A class Cat extends Animal does not override makeSound(). What are your two options to make it compile?
Show answer
Either add a makeSound() method with a body to Cat, or declare Cat as abstract.