Inheritance, abstract classes and interfaces
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Is-a relationships
Inheritance lets a class take on the fields and methods of another. A Dog is an Animal, so Dog can extend Animal and add or change behaviour. Java allows a class to extend exactly one class, but to implement many interfaces.
Interfaces: a contract
An interface lists methods that a class promises to provide. It says what, not how. Code that depends on the interface works with any class that implements it. This is the main tool for making code flexible, and I use it far more than inheritance.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Notifier> notifiers = List.of(
new EmailNotifier("noreply@example.com"),
new SmsNotifier(),
new ConsoleNotifier());
for (Notifier n : notifiers) {
n.send("sara@example.com", "Your order has shipped."); // polymorphism
}
notifiers.get(0).sendAll(List.of("a@example.com", "b@example.com"), "Maintenance tonight");
System.out.println();
List<Employee> staff = List.of(
new Manager("Hina", 9000, 3),
new Developer("Omar", 7000, "Java"),
new Developer("Zara", 7500, "Kotlin"));
double total = 0;
for (Employee e : staff) {
System.out.println(e.describe());
total += e.monthlyPay();
}
System.out.println("Payroll: " + total);
// Pattern matching for instanceof (Java 16+)
for (Employee e : staff) {
if (e instanceof Developer d) {
System.out.println(d.name() + " writes " + d.language());
}
}
}
interface Notifier {
void send(String to, String message);
// A default method gives implementers behaviour for free
default void sendAll(List<String> recipients, String message) {
for (String r : recipients) {
send(r, message);
}
}
}
static class EmailNotifier implements Notifier {
private final String from;
EmailNotifier(String from) { this.from = from; }
@Override
public void send(String to, String message) {
System.out.println("EMAIL from " + from + " to " + to + ": " + message);
}
}
static class SmsNotifier implements Notifier {
@Override
public void send(String to, String message) {
System.out.println("SMS to " + to + ": " + message);
}
}
static class ConsoleNotifier implements Notifier {
@Override
public void send(String to, String message) {
System.out.println("[console] " + to + " - " + message);
}
}
static abstract class Employee {
private final String name;
protected final double baseSalary;
protected Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
}
String name() { return name; }
// Subclasses must supply this
abstract double monthlyPay();
// Shared code that uses the abstract method
String describe() {
return getClass().getSimpleName() + " " + name + " earns " + monthlyPay();
}
}
static class Manager extends Employee {
private final int teamSize;
Manager(String name, double baseSalary, int teamSize) {
super(name, baseSalary); // must be the first statement
this.teamSize = teamSize;
}
@Override
double monthlyPay() {
return baseSalary + teamSize * 200;
}
}
static class Developer extends Employee {
private final String language;
Developer(String name, double baseSalary, String language) {
super(name, baseSalary);
this.language = language;
}
String language() { return language; }
@Override
double monthlyPay() {
return baseSalary;
}
@Override
String describe() {
return super.describe() + " (" + language + ")";
}
}
}
Walking through it
The Notifier interface has one required method and one default method. Three classes implement it. The loop in main holds them all in a List<Notifier> and calls send. Each object runs its own version. This is polymorphism: the variable's type decides which methods you can call, and the object's real class decides which code runs. To add a Telegram notifier, you write one more class. The loop does not change. This is how large systems stay open to new features.
The @Override annotation is not required, but always use it. It asks the compiler to check that you really override something. If you misspell the method name or get a parameter type wrong, you get a compile error instead of a silent new method.
Employee is an abstract class. It cannot be instantiated with new. It holds shared fields and code, and declares monthlyPay as abstract, so every subclass must define it. The method describe in the base class calls monthlyPay, and Java runs the version of the actual object. This arrangement is known as the template method pattern.
A subclass constructor must call a superclass constructor with super(...), and that call must come first. If you do not write one, Java calls the no-argument constructor of the parent, and that fails to compile when the parent has none. Developer overrides describe and calls super.describe() to extend the parent's behaviour rather than replace it.
The access level protected means the member is visible to subclasses and to other classes in the same package. The checks in instanceof Developer d let you use the object as a Developer inside the if without a manual cast.
Interface or abstract class
- Use an interface for a capability that unrelated classes can share, or when you expect many implementations. A class can implement several.
- Use an abstract class when related classes share real state and code, and you want to force them to fill in some steps.
Prefer composition
Deep inheritance trees become fragile. A change in the base class can break any subclass. When you only want to reuse behaviour, and the relationship is "has a" rather than "is a", hold another object in a field and call its methods. A Car has an Engine. It is not an engine. I follow a simple rule: inheritance for a stable, shallow "is a" relationship, composition for the rest.
Common mistakes
- Inheriting just to reuse a method. That creates a false "is a" relationship.
- Forgetting
@Override. - Calling an overridable method from a constructor. The subclass may not be initialised yet.
- Overloading when you meant to override. The parameter types differ slightly, so the base version still runs.
- Casting without checking. A wrong cast throws
ClassCastException. Useinstanceoffirst.
Try it yourself
- Create an interface
Discountwithdouble apply(double price). ImplementPercentDiscountandFixedDiscount. - Write an abstract class
Shapewith an abstractarea()and addCircleandRectangle. - Put the shapes in a list and print the one with the largest area.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Notifier> notifiers = List.of(
new EmailNotifier("noreply@example.com"),
new SmsNotifier(),
new ConsoleNotifier());
for (Notifier n : notifiers) {
n.send("sara@example.com", "Your order has shipped."); // polymorphism
}
notifiers.get(0).sendAll(List.of("a@example.com", "b@example.com"), "Maintenance tonight");
System.out.println();
List<Employee> staff = List.of(
new Manager("Hina", 9000, 3),
new Developer("Omar", 7000, "Java"),
new Developer("Zara", 7500, "Kotlin"));
double total = 0;
for (Employee e : staff) {
System.out.println(e.describe());
total += e.monthlyPay();
}
System.out.println("Payroll: " + total);
// Pattern matching for instanceof (Java 16+)
for (Employee e : staff) {
if (e instanceof Developer d) {
System.out.println(d.name() + " writes " + d.language());
}
}
}
interface Notifier {
void send(String to, String message);
// A default method gives implementers behaviour for free
default void sendAll(List<String> recipients, String message) {
for (String r : recipients) {
send(r, message);
}
}
}
static class EmailNotifier implements Notifier {
private final String from;
EmailNotifier(String from) { this.from = from; }
@Override
public void send(String to, String message) {
System.out.println("EMAIL from " + from + " to " + to + ": " + message);
}
}
static class SmsNotifier implements Notifier {
@Override
public void send(String to, String message) {
System.out.println("SMS to " + to + ": " + message);
}
}
static class ConsoleNotifier implements Notifier {
@Override
public void send(String to, String message) {
System.out.println("[console] " + to + " - " + message);
}
}
static abstract class Employee {
private final String name;
protected final double baseSalary;
protected Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
}
String name() { return name; }
// Subclasses must supply this
abstract double monthlyPay();
// Shared code that uses the abstract method
String describe() {
return getClass().getSimpleName() + " " + name + " earns " + monthlyPay();
}
}
static class Manager extends Employee {
private final int teamSize;
Manager(String name, double baseSalary, int teamSize) {
super(name, baseSalary); // must be the first statement
this.teamSize = teamSize;
}
@Override
double monthlyPay() {
return baseSalary + teamSize * 200;
}
}
static class Developer extends Employee {
private final String language;
Developer(String name, double baseSalary, String language) {
super(name, baseSalary);
this.language = language;
}
String language() { return language; }
@Override
double monthlyPay() {
return baseSalary;
}
@Override
String describe() {
return super.describe() + " (" + language + ")";
}
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account