Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 11

Programming to an interface

implements alongside extends, and why method parameters should be contracts

24m60 XP
→→→

What you'll be able to do

  • Combine `extends` and `implements` in one class declaration
  • Treat an interface as the declared type of variables, parameters and fields
  • Add a new implementation without editing any existing code
  • Explain why interface polymorphism is looser than class inheritance
1

The implements Keyword

extends once, implements as often as you like

A class declaration may carry both keywords, always in this order: ``java class Duck extends Animal implements Swimmable { ` Read it as two separate statements: *Duck is a kind of Animal* (single inheritance of state and code) and *Duck is capable of swimming* (a contract it signs). One object can therefore be viewed through three different types — Duck, Animal, and Swimmable` — and each view exposes a different slice of its members while the object itself never changes.

One object, three views

Try `asAnimal.swim();` — it fails, because the Animal view does not include the swimming contract, even though the object can swim.

Output
Press Run to execute this example.

extends vs implements

extendsimplements
ReadingIS-A kind ofCAN-DO / is capable of
How many?exactly one classany number of interfaces
Inherits code?yes (methods + fields)only default methods; never fields
Inherits state?yesno — interfaces have no instance state
Typical useshare an implementationshare a capability across unrelated types

An interface may extend another interface

interface Duckish extends Swimmable, Flyable { } is legal — interfaces use extends with each other, and may extend several at once. The 'only one parent' rule applies to *classes*.

Prove it — coding challenges

2

Polymorphism with Interfaces

Depend on the contract, not on the class

The single most valuable habit in this course: declare variables, parameters and fields with the *interface* type, and create the concrete class in exactly one place.

Compare two versions of the same service: ``java class AlertService { private EmailNotifier notifier; // ❌ welded to one class } class AlertService { private Notifier notifier; // ✅ any implementation fits } ` The second version can send by email, SMS, push or a fake notifier in tests — and AlertService never changes a single line. The class it uses is chosen by whoever constructs it, which is *dependency injection* in its simplest form. This is also what makes code testable: in a unit test you pass a FakeNotifier` that just records the message, with no network involved.

Swap the implementation, keep the code

Add a `PushNotifier` printing `Push: ...` and create a third AlertService with it. Notice that `AlertService` itself needs no edit — that is the whole point.

Output
Press Run to execute this example.

Abstract class or interface for this job?

Interface fits

capability, no shared state

  • Implementations are unrelated types
  • You need several capabilities on one class
  • You want to swap implementations, including fakes in tests
  • Examples: Notifier, Comparable, Runnable, Payable

Abstract class fits

family with shared state

  • Subtypes genuinely form one family
  • There are common fields to store
  • There is a shared algorithm to protect
  • Examples: Account, Shape, Employee

They are not rivals

Real designs use both: abstract class Account implements Transferable. The abstract class supplies shared state and code; the interface advertises a capability that classes outside the family can also provide.

Common mistakes

Wrongclass Duck implements Swimmable extends Animal
WhyWrong order — `extends` must come first.
Fixclass Duck extends Animal implements Swimmable
WrongDeclaring fields and parameters with the concrete class (`EmailNotifier notifier;`).
WhyEvery change of implementation forces edits in the consumer class.
FixDeclare the interface type and pass the implementation in the constructor.
WrongCreating an interface for a type that will only ever have one implementation.
WhyExtra indirection with no benefit; abstraction has a cost too.
FixIntroduce the interface when a second implementation (or a test fake) actually appears.

Lesson playground

Free practice

A pricing policy chosen at construction time. Add a `Student` policy taking 50% off and check out with it.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

The service depends on the interface. What is printed?

Main.java
1interface Logger {
2 void log(String text);
3}
4
5class ConsoleLogger implements Logger {
6 @Override
7 public void log(String text) {
8 System.out.println("console: " + text);
9 }
10}
11
12class PrefixLogger implements Logger {
13 @Override
14 public void log(String text) {
15 System.out.println(">> " + text);
16 }
17}
18
19class App {
20 private Logger logger;
21
22 App(Logger logger) {
23 this.logger = logger;
24 }
25
26 void run() {
27 logger.log("started");
28 }
29}
30
31public class Main {
32 public static void main(String[] args) {
33 new App(new ConsoleLogger()).run();
34 new App(new PrefixLogger()).run();
35 }
36}

Summary

  • `class X extends Y implements A, B` — one parent, any number of contracts, in that order.
  • An object can be viewed through its class, its parents and each of its interfaces.
  • Declare fields and parameters with the interface type; choose the implementation at construction.
  • Interfaces let you add new behaviour without modifying existing code — or test with fakes.