Programming with Java
Lesson 3 of 4 8 min +55 XP

Interfaces & Abstraction

Program to a contract, not an implementation.

What you'll learn

  • Define an interface
  • Distinguish an interface from a class
  • Explain why coding to an interface helps
Any plug that fits the socket

A wall socket doesn't care what brand the appliance is — anything with the right plug works. An interface is that socket: it names what a class must be able to do, so your code works with any object that fits the contract.

A promise about behavior

An interface in Java declares a set of method signatures without bodies — a contract that any implementing class must fulfill. A class 'implements' an interface by providing the actual code. This lets unrelated classes be used interchangeably as long as they honor the same contract.

Depend on the contract

If a method accepts a Comparable, it works with any type that implements Comparable — Integer, String, or your own class — without knowing the concrete type. That's abstraction reducing coupling.

interface Shape { double area(); } — both Circle and Square implement area(), so code can call shape.area() on either.
Lab · Swap the implementation
  1. A method takes a parameter of interface type Shape and calls area().
  2. You pass in a Circle, then later a Square.
  3. Explain why the method needs no changes.

What you should see: Both Circle and Square implement Shape's area() contract, so the method works with either — you can swap implementations freely.

Knowledge Check

+15 XP / correct

1. An interface in Java primarily defines…

2. Coding to an interface rather than a concrete class helps by…