Skip to content

Intermediate · Inheritance, polymorphism and interfaces · topic 23 of 60 · 20 min

Abstract classes

Explanation

An abstract class is a partial blueprint: it cannot be instantiated with new, and it can declare abstract methods (no body) that every concrete subclass must implement. It can also hold fields, constructors and finished methods. It suits families of classes that share state and some steps but differ in others.

Why abstract classes?

Some classes only make sense as a base for others. "A Payment" in general cannot be paid; only a UPI payment or a card payment can. Marking Payment abstract stops anyone from creating a plain Payment, and abstract methods force every real payment type to provide the missing behaviour.

java
public abstract class Payment {
    private final String orderId;
    protected final double amount;

    protected Payment(String orderId, double amount) {   // abstract classes can have constructors
        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
        this.orderId = orderId;
        this.amount = amount;
    }

    public final String process() {            // a fixed sequence of steps (template method)
        validate();
        String ref = charge();                 // the step each subclass fills in
        return "Order " + orderId + " paid, ref " + ref;
    }

    protected void validate() { }             // optional hook with a default
    protected abstract String charge();       // no body: subclasses MUST implement it
}

public class UpiPayment extends Payment {
    private final String vpa;
    public UpiPayment(String orderId, double amount, String vpa) { super(orderId, amount); this.vpa = vpa; }
    @Override protected void validate() { if (!vpa.contains("@")) throw new IllegalArgumentException("Bad UPI ID"); }
    @Override protected String charge() { return "UPI-" + System.nanoTime(); }
}

// Payment p = new Payment("O1", 100);      // compile error: Payment is abstract
Payment p = new UpiPayment("O1", 499, "asha@okbank");
System.out.println(p.process());

Rules

  • A class with at least one abstract method must itself be declared abstract.
  • An abstract class cannot be instantiated, but you can declare variables of its type (polymorphism).
  • A concrete (non-abstract) subclass must implement every inherited abstract method, or be abstract itself.
  • Abstract classes can have fields, constructors, static members and normal methods.

The template method pattern

process() above defines the fixed order of steps once (validate, then charge, then build the result) and lets subclasses fill in the variable steps. This pattern, called template method, is common in frameworks: the framework owns the flow, and you plug in the specific parts.

Careful: An abstract method has a semicolon and no braces: protected abstract String charge();. Writing empty braces {} makes it a normal method that does nothing, so subclasses are no longer forced to implement it, and a forgotten override silently does nothing at run time.
Think of it like this: An abstract class is like a standard exam answer sheet with printed sections (name, roll number, instructions) and blank boxes for answers. Nobody submits the blank template itself; each student (subclass) must fill in the answer boxes (abstract methods).
Tip: Use an abstract class when subclasses share state (fields) or constructor logic. If you only need a list of methods, an interface (next topic) is usually better, because a class can implement many interfaces but extend only one class.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Abstract classes · 1/6

Abstract classes

In this lesson you will write abstract classes, partial blueprints for families of classes.

Prefer a video by a teacher? Find free videos on “java abstract class abstract method template method pattern” on YouTube ↗

In real life: Report generators in a hospital system

A hospital system produces daily reports for the pharmacy, the lab and billing. An abstract Report class holds the date and the common header and footer and defines the generate() sequence; each subclass only implements its body section. Adding a radiology report means one new subclass.

java
abstract class Report {
    protected final java.time.LocalDate date;
    Report(java.time.LocalDate date) { this.date = date; }
    final String generate() { return "City Hospital – " + date + "\n" + body() + "\n-- end --"; }
    protected abstract String body();
}
class PharmacyReport extends Report {
    PharmacyReport(java.time.LocalDate d) { super(d); }
    protected String body() { return "Medicines dispensed: 412"; }
}

Practice (0/3 done)

Task 1 · Question

abstract class Shape { abstract double area(); } class Square extends Shape { } What happens?

Task 2 · Question

Which statement is TRUE about abstract classes?

Task 3 · Practice

Write an abstract class Shape with a name field, a constructor, an abstract double area() and a final method describe() that returns "<name> with area <area to 2 decimals>". Write Circle and Rectangle subclasses. Store them in a Shape[] and print each description.

Quick quiz

Question 1

1.How is an abstract method written?

Question 2

2.Can you declare a variable of an abstract class type?

Question 3

3.What is the template method pattern?

Question 4

4.A class has one abstract method but is not marked abstract. Result?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How is an abstract method written?

Answer: abstract void run();

Abstract methods end with a semicolon and have no body.

Can you declare a variable of an abstract class type?

Answer: Yes, and assign it a subclass object

Payment p = new UpiPayment(…) is polymorphism.

What is the template method pattern?

Answer: A fixed sequence of steps in a parent, with some steps filled in by subclasses

The parent owns the flow.

A class has one abstract method but is not marked abstract. Result?

Answer: Compile error

The class itself must be declared abstract.

Can an abstract class have a constructor and normal methods?Related

Answer: Yes

Abstract classes can contain state, constructors and implemented methods.

From Abstract classes and polymorphism

Which keyword allows a class to be inherited?Related

Answer: open

Classes are final unless marked open (or abstract).

From Inheritance and interfaces

Can an abstract class have a constructor and data members?Related

Answer: Yes; it just cannot be instantiated on its own

Abstract only means "cannot be created directly". It may still hold shared data and constructors for derived classes.

From Abstract classes, interfaces and good class design

How many interfaces can a class implement?Related

Answer: Many

Multiple interface implementation is allowed.

From Interfaces

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Inheritance, polymorphism and interfaces” before its exam: Interfaces, Packages and access modifiers.
  2. Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.

← Previous: Overriding and polymorphism