Skip to content

Module 6 · Inheritance, Polymorphism and Interfaces — topic 3 of 3

Abstract Classes and Interfaces

Abstract classes with partial implementations, interfaces as contracts, default and static interface methods, implementing several interfaces, functional interfaces and sealed types.

Beginner 18 min read·Lesson 22 of 39 in Java Programming

Learning objectives

  • Write abstract classes with abstract and concrete methods
  • Define and implement interfaces, including default methods
  • Choose between an abstract class and an interface

Definition

Abstraction exposes what an object does while hiding how. An abstract class cannot be instantiated and may contain abstract methods for subclasses to implement; an interface declares a contract of methods that any class can implement, regardless of its superclass.

Introduction

Some types are too general to exist on their own. There's no such thing as 'just a Shape' — every real shape is a circle, a square or something else. Abstract classes and interfaces let you describe what all shapes can do while leaving the details to concrete classes.

Why it matters

Interfaces are everywhere in Java: List, Comparable, Runnable, AutoCloseable. Writing code against interfaces makes it flexible and testable.

Knowing when to use an abstract class versus an interface is a classic design and interview question.

Detailed explanation

Abstract classes. Declared with abstract class. They can't be created with new, but they can have fields, constructors, concrete methods and abstract methods (no body) that every concrete subclass must implement. Use them when related classes share state and code.

Interfaces declare methods that implementing classes promise to provide: class Circle implements Shape. Interface methods are implicitly public abstract; fields are implicitly public static final constants.

Several interfaces. A class extends at most one class but can implement many interfaces: class Duck extends Bird implements Flyer, Swimmer. This is how Java gets the benefits of multiple inheritance of type without its complications.

default and static methods (Java 8). An interface can provide default methods with a body, which implementing classes inherit and may override, and static helper methods. Java 9 also allows private interface methods for sharing code between defaults.

Functional interfaces have exactly one abstract method — Runnable, Comparator, and your own interfaces marked @FunctionalInterface. They can be implemented with lambdas (module 10).

Choosing. Use an interface to define a capability that unrelated classes may share (Comparable, Printable). Use an abstract class to share code and state among closely related classes. They combine well: an interface for the contract and an abstract class with a partial implementation.

sealed (Java 17). sealed interface Shape permits Circle, Square restricts which classes may implement a type, so the compiler knows every possibility — useful with switch pattern matching.

Syntax

Java
abstract class Shape {
abstract double area(); // no body
String describe() { return getClass().getSimpleName() + " area " + area(); }
}
interface Resizable {
void scale(double factor); // public abstract
default void doubleSize() { scale(2); } // inherited implementation
}
class Circle extends Shape implements Resizable {
private double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
@Override public void scale(double f) { r *= f; }
}
  • A class with an abstract method must itself be abstract.
  • Implementing methods of an interface must be public.
  • An interface can extend other interfaces.

Code examples

An abstract class

Java
public class Main {
public static void main(String[] args) {
Shape[] shapes = {new Circle(1), new Rect(2, 3), new Circle(0.5)};
double total = 0;
for (Shape s : shapes) {
System.out.println(s.describe());
total += s.area();
}
System.out.printf("Total area %.2f%n", total);
}
}
abstract class Shape {
abstract double area();
abstract double perimeter();
String describe() { // concrete method using abstract ones
return String.format("%s: area %.2f, perimeter %.2f", getClass().getSimpleName(), area(), perimeter());
}
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
@Override double perimeter() { return 2 * Math.PI * r; }
}
class Rect extends Shape {
private final double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }
@Override double perimeter() { return 2 * (w + h); }
}
Output
Circle: area 3.14, perimeter 6.28
Rect: area 6.00, perimeter 10.00
Circle: area 0.79, perimeter 3.14
Total area 9.93

Interfaces with default methods

Java
public class Main {
public static void main(String[] args) {
Payment[] payments = {new Card("4111222233334444"), new Upi("asha@bank")};
for (Payment p : payments) {
System.out.println(p.pay(1500) + " | fee " + p.fee(1500));
}
}
}
interface Payment {
String pay(long amount);
default long fee(long amount) { return 0; } // most methods are free
}
class Card implements Payment {
private final String number;
Card(String number) { this.number = number; }
@Override public String pay(long amount) { return "Paid " + amount + " by card ending " + number.substring(number.length() - 4); }
@Override public long fee(long amount) { return amount * 2 / 100; }
}
class Upi implements Payment {
private final String id;
Upi(String id) { this.id = id; }
@Override public String pay(long amount) { return "Paid " + amount + " via UPI " + id; }
}
Output
Paid 1500 by card ending 4444 | fee 30
Paid 1500 via UPI asha@bank | fee 0

More examples

Several interfaces, a functional interface and a sealed type

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Product> items = new ArrayList<>(List.of(new Product("Laptop", 55_000), new Product("Mouse", 600), new Product("Desk", 7_500)));
Collections.sort(items); // uses Comparable
for (Product p : items) System.out.println(p.label());
Discount festive = price -> price * 90 / 100; // lambda implements the functional interface
Discount flat = price -> Math.max(0, price - 500);
System.out.println("festive: " + festive.apply(7_500) + ", flat: " + flat.apply(7_500) + ", both: " + festive.andThen(flat).apply(7_500));
List<Vehicle> fleet = List.of(new Car(4), new Bike(), new Car(7));
for (Vehicle v : fleet) System.out.println(v.getClass().getSimpleName() + " toll " + toll(v));
}
static int toll(Vehicle v) {
return switch (v) { // exhaustive: Vehicle is sealed
case Car c -> c.seats() > 5 ? 120 : 80;
case Bike b -> 20;
};
}
}
interface Labelled {
String name();
default String label() { return "[" + name() + "]"; }
}
class Product implements Comparable<Product>, Labelled {
private final String name;
private final int price;
Product(String name, int price) { this.name = name; this.price = price; }
@Override public String name() { return name; }
@Override public String label() { return Labelled.super.label() + " Rs " + price; }
@Override public int compareTo(Product o) { return Integer.compare(price, o.price); }
}
@FunctionalInterface
interface Discount {
int apply(int price);
default Discount andThen(Discount next) { return p -> next.apply(apply(p)); }
}
sealed interface Vehicle permits Car, Bike { }
record Car(int seats) implements Vehicle { }
record Bike() implements Vehicle { }
Output
[Mouse] Rs 600
[Desk] Rs 7500
[Laptop] Rs 55000
festive: 6750, flat: 7000, both: 6250
Car toll 80
Bike toll 20
Car toll 120

Step-by-step explanation

  • Product implements two interfaces: Comparable (so Collections.sort can order products by price) and Labelled.
  • Labelled.super.label() calls the interface's default method from inside the override, then adds the price.
  • Discount has one abstract method, so lambdas such as price -> price * 90 / 100 implement it; its default andThen composes two discounts (7500 → 6750 → 6250).
  • sealed interface Vehicle permits Car, Bike lists every allowed implementation; Car and Bike are records, which are implicitly final.
  • Because the compiler knows all Vehicle types, the pattern-matching switch in toll needs no default case.

Expected output

Running “Several interfaces, a functional interface and a sealed type” prints exactly:

TextOutput
[Mouse] Rs 600
[Desk] Rs 7500
[Laptop] Rs 55000
festive: 6750, flat: 7000, both: 6250
Car toll 80
Bike toll 20
Car toll 120

Practical applications

  • The Collections Framework: List, Set and Map are interfaces with several implementations
  • JDBC: your code uses Connection and ResultSet interfaces implemented by each database driver
  • Comparable and Comparator for sorting, Runnable and Callable for threads
  • Abstract base classes such as AbstractList that make writing new collections easy

Best practices

  • Declare variables and parameters with interface types (List, not ArrayList).
  • Keep interfaces small and focused on one capability.
  • Use an abstract class only when implementations really share state or code.

Common mistakes

Trying to instantiate an abstract type

Avoid

Shape s = new Shape();

Prefer

Shape s = new Circle(2);

Abstract classes and interfaces describe incomplete types; create a concrete subclass instead.

Reducing visibility of an interface method

Avoid

class Card implements Payment {
String pay(long amount) { ... } // package-private
}

Prefer

class Card implements Payment {
public String pay(long amount) { ... }
}

Interface methods are public, and an implementation can't be less accessible than the method it implements.

Important notes

  • If a class inherits the same default method from two interfaces, it must override it and may choose one with InterfaceName.super.method().
  • Sealed classes and interfaces became standard in Java 17; pattern matching for switch in Java 21.

Key takeaways

  • Abstract classes can't be instantiated and may mix abstract and concrete methods.
  • Interfaces define contracts; a class can implement many and inherit default methods.
  • Functional interfaces have one abstract method and can be implemented with lambdas.

Try it yourself

  1. 1
    Define an interface Taxable with tax() and a default priceWithTax(price), and implement it for two product types.
  2. 2
    Create an abstract Game class with a template method play() that calls abstract start, turn and end steps.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

9 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhy doesn't `Shape s = new Shape();` compile when Shape is abstract?
  • BeginnerHow many interfaces can a class implement?
  • BeginnerWhat is printed?
Practise this topic