Reading history

Java Interfaces and Abstract Classes (with Examples)

5 min read 0 views

Learn Java interfaces and abstract classes: implements, default methods, abstract methods, multiple interfaces, and how to choose between an interface and an abstract class.

Interfaces and abstract classes let you describe what a group of classes must be able to do while leaving how to each class. They are the main tools for abstraction in Java and the reason one method can work with a circle, a rectangle or any future shape without changing. This lesson shows how to write both, how they differ, and how to choose between them.

In this lesson you will learn

  • Declaring and implementing an interface
  • Default methods in interfaces
  • Abstract classes and abstract methods
  • Implementing several interfaces at once
  • Interface vs abstract class: when to use which

This lesson builds on Inheritance and Polymorphism.

Interfaces

interface Shape {
    double area();                       // abstract by default
    default String describe() {          // default method with a body
        return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
    }
}

class Circle implements Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}

class Rectangle implements Shape {
    private final double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    public double area() { return w * h; }
}

public class Main {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1.5), new Rectangle(4, 2.5) };
        double total = 0;
        for (Shape s : shapes) {
            System.out.println(s.describe());
            total += s.area();
        }
        System.out.printf("Total area: %.2f%n", total);
    }
}

Output

Circle with area 7.07
Rectangle with area 10.00
Total area: 17.07
  • An interface is a contract. Shape says every shape has an area() method, but gives no body. Methods without a body in an interface are automatically public abstract.
  • A class signs the contract with implements and must provide every abstract method, otherwise it will not compile. The implementing method must be public.
  • A default method (Java 8+) has a body. describe() is inherited by every shape for free, and a class can override it.
  • The array type is Shape[]: the loop treats every object as a Shape, and Java calls the right area() at run time. That is polymorphism through an interface.

Abstract Classes

abstract class Account {
    private final String owner;
    protected double balance;

    Account(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    abstract double monthlyFee();         // each subclass decides

    void endOfMonth() {                   // shared logic
        balance -= monthlyFee();
        System.out.printf("%s: fee %.1f, balance %.1f%n", owner, monthlyFee(), balance);
    }
}

class Savings extends Account {
    Savings(String owner, double b) { super(owner, b); }
    double monthlyFee() { return 0; }
}

class Current extends Account {
    Current(String owner, double b) { super(owner, b); }
    double monthlyFee() { return balance < 5000 ? 50 : 10; }
}

interface Printable { void print(); }
interface Exportable { String export(); }

class Report implements Printable, Exportable {   // many interfaces allowed
    public void print() { System.out.println("Printing report"); }
    public String export() { return "report.csv"; }
}

public class Main {
    public static void main(String[] args) {
        Account[] accounts = { new Savings("Nadia", 12000), new Current("Rafi", 3000) };
        for (Account a : accounts) a.endOfMonth();

        Report r = new Report();
        r.print();
        System.out.println("Exported to " + r.export());
        // Account a = new Account("x", 0);  // error: Account is abstract
    }
}

Output

Nadia: fee 0.0, balance 12000.0
Rafi: fee 50.0, balance 2950.0
Printing report
Exported to report.csv
  • An abstract class is a partly built class. Account has real fields, a constructor and a finished method endOfMonth(), plus one abstract method that subclasses must fill in.
  • You cannot create an object of an abstract class with new; you create objects of its concrete subclasses.
  • This pattern, where shared code calls a step that subclasses define, is called the template method pattern.
  • Report implements two interfaces. A class can extend only one class but can implement any number of interfaces.

Interface vs Abstract Class

FeatureInterfaceAbstract class
Keyword to use itimplementsextends
How many per classManyOne
Instance fieldsNo (only public static final constants)Yes
ConstructorsNoYes
Method bodiesdefault, static and private methodsAny
Best forA capability unrelated classes share (“can be printed”)A family of closely related classes sharing state and code

A good rule: start with an interface. Add an abstract class when several implementations need the same fields or helper code.

Common Mistakes

  1. Forgetting public on a method that implements an interface method, which causes “attempting to assign weaker access privileges”.
  2. Trying to instantiate an abstract class or interface with new.
  3. Not implementing every abstract method, unless the class itself is declared abstract.
  4. Putting state in an interface: variables declared there are constants, not per-object fields.

Practice Exercises

Exercise 1. Add a Triangle class (base and height) that implements Shape.

Show answer
class Triangle implements Shape {
    private final double b, h;
    Triangle(double b, double h) { this.b = b; this.h = h; }
    public double area() { return 0.5 * b * h; }
}

No other code changes: the loop and describe() work with it immediately.

Exercise 2. Write an interface Discountable with a method double discount() and a default method double finalPrice(double price) that subtracts the discount.

Show answer
interface Discountable {
    double discount();
    default double finalPrice(double price) {
        return price - discount();
    }
}

Frequently Asked Questions

Can an interface extend another interface?

Yes, with extends, and it can extend several: interface Document extends Printable, Exportable.

What happens if two interfaces have the same default method?

The class must override the method to resolve the conflict. Inside, it can call a specific version with Printable.super.method().

Summary

  • An interface declares abilities; classes implements it and provide the code.
  • An abstract class is a partly finished parent with fields, constructors and abstract methods.
  • A class extends one class but can implement many interfaces.
  • Program against the interface type so new implementations plug in easily.

Next: Java ArrayList.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *