Abstract Classes
An abstract class can hold shared code while leaving selected methods for subclasses to implement. You cannot instantiate the abstract class itself.
This is useful when related classes share implementation and also need a required variation such as an alert message.
Require a subclass method
abstract class Alert {
abstract String message();
void send() {
System.out.println("ALERT: " + message());
}
}
class LowBattery extends Alert {
@Override
String message() {
return "Charge soon";
}
}
public class Main {
public static void main(String[] args) {
Alert alert = new LowBattery();
alert.send();
}
}
Output:
ALERT: Charge soon
Alert supplies the shared send method but requires each subclass to provide a message. LowBattery fulfills that requirement.
A concrete subclass must implement every inherited abstract method unless that subclass is abstract too.
Make Vehicle abstract, declare wheels as abstract, and make Bike return 2 wheels.