The Plain Picture#
A form with some fields pre-filled and some left blank with a note: "each department must fill this in". You can't submit the half-empty form itself — each department must complete it first.
The Real Names#
Abstraction = showing only what something does, hiding how. Code that uses
Questiononly knows "you can grade me".An abstract class is a class marked
abstractthat can't be instantiated (new Question(...)is a compile error). It exists to be extended.An abstract method has no body — only a signature ending in
;— and every concrete (non-abstract) subclass must implement it.An abstract class can still have fields, constructors and normal methods — the pre-filled parts of the form.
abstract class Question {
protected final String text; // shared state
protected final int points;
Question(String text, int points) { ... } // constructor used by subclasses via super(...)
abstract boolean isCorrect(String answer); // the blank each subclass must fill in
int grade(String answer) { // pre-filled logic that USES the blank
return isCorrect(answer) ? points : 0;
}
}grade is written once and relies on isCorrect, which each subclass provides. This shape — the parent defines the steps, subclasses fill
in specific steps — is the Template Method design pattern (Behavioural Patterns (coming soon)).
Check yourself
3 questionsCan you create an object of an abstract class?
Show answerHide answer
No.
What must a concrete subclass do with an abstract method?
Show answerHide answer
Implement (override) it with a body.
Can an abstract class have a constructor? Why would it?
Show answerHide answer
Yes — subclasses call it with super(...) to set up the shared fields.