Abstract Classes
An abstract class can declare abstract methods, like interface methods, with no body — but unlike an interface, it can also hold real fields and fully-implemented methods, and a subclass only has to implement the abstract parts. Vehicle can't be instantiated directly with new; only a concrete subclass like Car, which supplies describe(), can be.
public class Main {
static abstract class Vehicle {
abstract String describe();
void printDescription() {
System.out.println(describe());
}
}
static class Car extends Vehicle {
String describe() {
return "A car with four wheels";
}
}
public static void main(String[] args) {
Vehicle v = new Car();
v.printDescription();
}
}A car with four wheels
printDescription() is fully implemented in Vehicle itself and inherited by Car unchanged, while describe() has to come from whichever concrete subclass extends Vehicle — abstract classes let you share real code alongside the contract, which a plain interface can't do for you.
Next: exception handling — try, catch, checked exceptions, and what a real unreported-exception compile error looks like.
Practice exercise
Define an abstract class Shape with an abstract method area(). Define a class Square that extends Shape with a field side and an area() method returning side * side. Create a Square with side 5 and print its area().