Intermediate · Inheritance, polymorphism and interfaces · topic 23 of 60 · 20 min
Abstract classes
Explanation
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.
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.
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
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.
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)
abstract class Shape { abstract double area(); } class Square extends Shape { } What happens?
Which statement is TRUE about abstract classes?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- InterfacesInheritance, polymorphism and interfaces · same module
- Abstract classes and polymorphismC# and .NET · Inheritance, interfaces and records
- Inheritance and interfacesKotlin and Android App Development · Classes, objects and collections
- Abstract classes, interfaces and good class designC++ Programming (modern C++ and DSA) · Operator overloading, inheritance and polymorphism
- Inheritance, interfaces, mixins and extensionsFlutter and Dart · Null safety and object-oriented Dart
- Classes, objects and constructorsC# and .NET · Classes and objects
Questions people ask about this
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.
Which keyword allows a class to be inherited?Related
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.
How many interfaces can a class implement?Related
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
- 2 more topics in “Inheritance, polymorphism and interfaces” before its exam: Interfaces, Packages and access modifiers.
- Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.