Abstract classes and interfaces
On this page 8 topics
Overview
Topics
- Abstract methods
- interface contracts
- default methods
Learn first
64 min of reading · 3 h of practice (estimate)
Learning outcomes
- Declare an interface as a contract and implement it in several classes.
- Write an abstract class with shared state and abstract methods.
- Choose between an interface and an abstract class for a given scenario.
- Use default methods and explain their purpose and risks.
Lessons
Lab and exercises
Lab
BEG-024-LAB1 · Notification channels
Outcomes: 1, 3 · Time: ~2 h Create a Notifier interface with Email, SMS, and Console implementations. The bank sends statements through any Notifier. Add one test or main that runs the same statement through all three. Acceptance: the bank class depends only on the interface.
Exercises (assessment: 4 exercises plus a design question)
| ID | Outcome | Task |
|---|---|---|
| BEG-024-EX01 | 1 | Declare Shape with double area() and implement it in Circle and Rectangle. |
| BEG-024-EX02 | 2 | Write an abstract Employee with name, a constructor, and abstract double pay(); implement Salaried and Hourly. |
| BEG-024-EX03 | 4 | Add a default String describe() to Shape that returns "Area: " + area(). Name one risk of default methods. |
| BEG-024-EX04 | 3 | Interface or abstract class? (a) Flyable for birds and planes, (b) a base Vehicle with shared speed and fuel fields. |
| BEG-024-EX05 | 3 | Design question: a report system must export to PDF, CSV, and later more formats. Sketch the types and justify interface vs abstract class. |
Show solutions
- EX01
interface Shape { double area(); };CirclereturnsMath.PI * r * r;Rectanglereturnsw * h. - EX02
abstract class Employee { protected final String name; Employee(String n) { name = n; } abstract double pay(); }with two subclasses overridingpay. - EX03
default String describe() { return "Area: " + area(); }. Risk: conflicts when two interfaces define the same default, and logic hidden in interfaces. - EX04 (a) interface (unrelated types share a capability); (b) abstract class (shared state).
- EX05
interface ReportExporter { void export(Report r); }withPdfExporter,CsvExporter; add an abstract helper only if they share real code. New formats are new classes. - Outcome 1 is also covered by the lab.
Quiz
Outcomes: O1 interfaces · O2 abstract classes · O3 choosing · O4 default methods.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
Four exercises plus the design question (BEG-024-EX01 to EX05) and the notification lab. Pass: at least four of five correct and the bank class depends only on Notifier.
Common mistakes
Interfaces with a single "god" method; abstract classes used where an interface suffices.
Assessment
4 exercises plus a design question.
Career relevance
Every Spring repository and service boundary (JNR-009, JNR-029) is an interface.