Abstract classes and abstract methods¶
โ Java 17 ยท Blueprints You Can't Instantiate ยท 1/3
You know how a child class extends a parent and overrides its methods. Now the parent itself becomes a blueprint that nobody can create.
A parent nobody can create¶
On a streaming platform, every piece of content has a title, a format and a running time, and every piece can be played. But a plain Content object makes no sense: what people watch is a Movie or a Series.
So you mark Content as abstract:
| Class | Kind | new allowed? |
|---|---|---|
Content |
abstract: the shared blueprint | โ |
Movie |
extends Content, fills in the details |
โ |
Series |
extends Content, its own running time |
โ |
You still write the shared code once, in the parent. Each child is forced to provide the pieces only it knows. And the rest of the program can work with the Content type while the real object decides what happens.
Your first abstract class¶
abstract class Content {
abstract String format();
void play() {
System.out.println("Playing " + format());
}
}
class Movie extends Content {
String format() { return "HD movie"; }
}
public class Main {
public static void main(String[] args) {
new Movie().play();
// new Content(); // โ Content is abstract; cannot be instantiated
}
}
abstract class Content: the class can't be created withnew.abstract String format();is an abstract method: a return type, a name, parentheses, then a semicolon. No body at all.play()is a normal method. It can already callformat(), even thoughContentdoesn't know howformat()works.Moviekeeps the promise by writing the body. Callingplay()on a movie runsContent'splay(), which callsMovie'sformat().
Where abstract is allowed¶
The keyword can't go just anywhere:
class Podcast {
abstract void play(); // โ abstract method in a normal class
}
abstract class Content {
abstract String title; // โ fields can't be abstract
abstract Content(); // โ constructors can't be abstract
}
- An abstract method can only live in an abstract class.
- Only methods can be abstract: never fields, never constructors.
An abstract class can contain everything a normal class contains, and it doesn't even need an abstract method:
abstract class Content {
abstract int length();
String title;
void share() { }
}
abstract class Short { // โ
no abstract method, still abstract
void play() { }
}
new Short() doesn't compile either: an abstract class is never created directly, whatever it contains.
The modifier order is flexible with access modifiers: abstract public class and public abstract class both work. But abstract never comes after the word class, or after a method's return type.
Next, who has to write the missing bodies, and what the compiler refuses.
๐ป Code: Java17_Part_6_Object_Oriented_Basics on GitHub
โ Series overview ยท Next: concrete classes and the rules โ