Java · Intermediate level

Intermediate level · Module 1: Inheritance, Interfaces and Polymorphism · Lesson 2 of 3

Abstract Classes and Interfaces

Define shared contracts with interfaces, share partial implementations with abstract classes, and choose between them.

In this lesson you will

  • Write interfaces and classes that implement them
  • Decide when an abstract class or an interface is the better tool

Key concepts

interfaceimplementsabstract methoddefault method

The lesson

An interface lists methods a class promises to provide: interface PaymentMethod { boolean pay(double amount); String name(); }. A class can implement many interfaces, which makes interfaces the main tool for describing capabilities.

An abstract class cannot be instantiated and may contain both implemented methods and abstract ones without a body. Use it when related classes share state or code, for example an abstract Shape with a name field and an abstract area() method.

Interfaces can include default methods with a body, which helps when adding behaviour to an interface without breaking existing classes. Prefer interfaces for contracts and keep abstract classes for genuinely shared implementation.

Step by step

  1. Write a PaymentMethod interface with pay() and name().
  2. Implement CashPayment and MobileMoneyPayment.
  3. Add a default method receipt(amount) to the interface.
  4. Write an abstract class Shape and two concrete shapes, and compare the designs.

Practice activity

Design a Notifier interface for sending reminders, with SmsNotifier and EmailNotifier implementations that print what they would send.

Expected result: Code that holds a Notifier can switch between SMS and email without any change.

Check your understanding

  1. Can a class implement more than one interface?

    Show answer

    Yes; it can implement several interfaces but extend only one class.

  2. When is an abstract class preferable to an interface?

    Show answer

    When related classes share fields or implementation code, not only method signatures.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.