Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Abstract Classes (Abstraction, Part 1)

    Abstraction — showing only what something does, hiding how. Code that uses Question only knows "you can grade me".

    Chapter 5 of 122 min read

    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 Question only knows "you can grade me".

    • An abstract class is a class marked abstract that 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.

    Java
    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 questions
    1

    Can you create an object of an abstract class?

    Show answer

    No.

    2

    What must a concrete subclass do with an abstract method?

    Show answer

    Implement (override) it with a body.

    3

    Can an abstract class have a constructor? Why would it?

    Show answer

    Yes — subclasses call it with super(...) to set up the shared fields.