Filling the gaps: concrete classes and the rules¶
โ Java 17 ยท Blueprints You Can't Instantiate ยท 2/3
An abstract class leaves gaps. This page shows who fills them, how its constructor still runs, and which declarations never compile.
The first concrete class fills the gaps¶
A concrete class is a class that is not abstract. The first concrete class in a family must implement every abstract method that is still left.
abstract class Content {
abstract String format();
abstract int minutes();
}
abstract class Series extends Content {
int minutes() { return 45; } // fills one gap, skips format()
}
class Anime extends Series {
String format() { return "SUB"; } // fills what is left
}
| Class | Abstract? | Must implement |
|---|---|---|
Content |
yes | nothing: declares format() and minutes() |
Series |
yes | nothing: implements minutes(), may skip format() |
Anime |
no | format(), still abstract; minutes() is already done |
If Anime skips format(), it no longer compiles: Anime is not abstract and does not override abstract method format().
Abstract classes still have constructors¶
You can't create an abstract class, but it can declare constructors. They run every time a child object is built:
abstract class Content {
Content() {
System.out.println("Content ready: " + format());
}
abstract String format();
}
class Movie extends Content {
String format() { return "4K"; }
}
public class Main {
public static void main(String[] args) {
new Movie();
}
}
new Movie() calls the Movie constructor, which first calls super(): the Content constructor runs, and format() resolves to Movie's version. With no constructor written, the compiler adds the default one, as in any class.
Broken abstract methods¶
abstract class Trailer {
abstract long length() // โ no semicolon
abstract void play() { } // โ has a body
abstract void pause; // โ no parentheses
void stop(); // โ not abstract, no body
}
- An abstract method ends with a semicolon.
- It never has braces, not even empty ones:
{ }is a body. - A method without
abstractalways needs a body.
Three forbidden partners¶
abstract final class Show { } // โ
abstract class Clip {
private abstract void cut(); // โ
static abstract void trim(); // โ
final abstract void crop(); // โ
}
| Pair | Why it can't work |
|---|---|
abstract + final |
must be extended vs can't be extended |
abstract + private |
not inherited, so no child could implement it |
abstract + static |
static methods can't be overridden, so no body ever |
The fixed version keeps each intent without the contradiction:
The lab puts it all together in a small catalog built on two abstract classes.