abstract methods
- Java course
- Intermediate
- Lesson 54/116
- 5 min
Learn abstract methods.
abstract methods
An abstract method is a method declaration without a body. It starts with the abstract keyword; the subclass must write its body.
Example: abstract void sound();. Here sound has a signature; no body. It is declared inside an abstract class. A subclass overrides this method and writes its body. Otherwise the subclass itself must be abstract. This mechanism lets the base class say what to do; it leaves how to the subclass. Different subclasses can implement the same method differently. This is the basis of polymorphism.
The override requirement
Abstract methods of an abstract class must be overridden in the subclass. Otherwise the subclass itself must be abstract. This guarantees the contract is fulfilled.
Example: if you define abstract class Animal { abstract void sound(); } and then write class Dog extends Animal, you must write void sound() with its body. If you do not, the compiler gives an error like 'Dog is not abstract and does not override abstract method sound'. The @Override annotation strengthens this check. The subclass may also override concrete methods of the abstract class. But abstract methods must absolutely be written.
Practice Add an abstract sound method to Animal
Define an abstract class Animal. Add the abstract void sound(); signature. Write class Dog extends Animal; write the public void sound() method with a body that runs System.out.println("Woof woof");. In main call new Dog().sound().
Starter code
// Define the abstract Animal class
// Write the Dog subclass
// Call new Dog().sound() in mainSample solution
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
public void sound() {
System.out.println("Woof woof");
}
}
class Main {
public static void main(String[] args) {
new Dog().sound();
}
}Expected output
Woof woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the abstract method features
| Term | Meaning |
|---|---|
abstract |
Bodyless keyword |
; |
Signature end |
override |
Rewrite |
void sound() |
Signature example |
2 What must a class be to contain an abstract method?
- final
- static
- sealed
- abstract Correct answer
Explanation: An abstract method belongs only in an abstract class.
3 Complete the abstract method signature
abstract class Animal {
____ void sound();
}
abstract class Animal {
abstract void sound();
}
Explanation: The abstract keyword declares a bodyless method.