Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 11

Multiple interfaces, default & static methods

Many capabilities on one class — and the modern interface toolkit

26m60 XP
→→→

What you'll be able to do

  • Implement several interfaces on one class and use each view
  • Explain why multiple interfaces are safe while multiple superclasses are not
  • Use `default`, `static` and `private` methods inside an interface
  • Choose between an interface and an abstract class with a clear rule
1

Multiple Interfaces

A class can sign many contracts

A duck flies and swims. A plane only flies. A fish only swims. One inheritance tree cannot express that — two interfaces can.

class Duck implements Flyable, Swimmable — separate the interfaces with commas and implement every method of every one. Why is this allowed when extends A, B is not? Because of state. If two superclasses both had a field speed and a method move(), the object would carry two copies of the data and Java could not tell which move() you meant — the classic *diamond problem*. Interfaces (before Java 8) carry no data and no bodies, so there is nothing to duplicate: only the *requirement* is inherited, and one implementation satisfies both.

One duck, two contracts

Add `interface Quackable { void quack(); }` to Duck as a third contract, then call it through a `Quackable` reference.

Output
Press Run to execute this example.

Same signature in two interfaces? No problem

If Printable and Exportable both declare void render();, a class implementing both writes one render() method and it satisfies both contracts. There is no conflict, because neither interface supplied a body.

instanceof works with interfaces too
Main.java
1for (Payable method : methods) {
2 method.pay(100);
3
4 if (method instanceof Refundable) { // capability check
5 ((Refundable) method).refund(40);
6 }
7}
Asking 'can this object do X?' rather than 'what class is this?' is the one form of instanceof that stays clean as a design grows.

Prove it — coding challenges

2

Default Methods

default methods: bodies inside an interface

Java 8 added default methods so that an interface could gain a new method without breaking the thousands of classes that already implement it. A default method has a body; implementing classes inherit it and may override it. That backwards-compatibility problem is the real reason they exist — not as a replacement for abstract classes. An interface still has no instance fields, so a default method can only work with the other methods of the contract.

A contract with a free bonus method
Main.java
1interface Vehicle {
2 void start(); // must be implemented
3
4 default void honk() { // inherited for free
5 System.out.println("Beep beep!");
6 }
7}
8
9class Car implements Vehicle {
10 @Override
11 public void start() {
12 System.out.println("Car started");
13 }
14 // honk() inherited — no code needed
15}
16
17class Truck implements Vehicle {
18 @Override
19 public void start() {
20 System.out.println("Truck started");
21 }
22
23 @Override
24 public void honk() { // may override the default
25 System.out.println("HOOOONK!");
26 }
27}
Existing classes keep compiling when `honk()` is added, because the interface ships an implementation with it.
When two defaults collide, you must choose
Main.java
1interface A {
2 default void hello() { System.out.println("A"); }
3}
4
5interface B {
6 default void hello() { System.out.println("B"); }
7}
8
9class C implements A, B {
10 @Override
11 public void hello() {
12 A.super.hello(); // pick one explicitly...
13 System.out.println("C");
14 }
15}
This is the only place the diamond problem reappears — and Java refuses to guess: the class must override the method. `A.super.hello()` names the version you want.
3

Static Interface Methods

static and private methods in interfaces

Helpers that belong to the contract itself
Main.java
1interface Validator {
2 boolean validate(String value);
3
4 static Validator notEmpty() { // Java 8: factory on the interface
5 return value -> value != null && !value.isEmpty();
6 }
7
8 default boolean validateAll(String[] values) {
9 for (String value : values) {
10 if (!check(value)) { // uses the private helper
11 return false;
12 }
13 }
14 return true;
15 }
16
17 private boolean check(String value) { // Java 9: shared by default methods
18 return validate(value);
19 }
20}
21
22// Called on the interface, never on an instance:
23// Validator v = Validator.notEmpty();
static interface methods are utilities that are not inherited by implementing classes; private interface methods exist only to remove duplication between default methods.

Four kinds of interface member

abstract (no keyword)
Signature only. Implementing classes must provide the body. The default kind.
default
Has a body, is inherited, may be overridden. Added in Java 8.
static
Has a body, called as InterfaceName.method(), not inherited.
private
Has a body, callable only inside the interface, used to share code between default methods. Added in Java 9.

Sandbox note

The in-browser Java engine used by the challenges focuses on the classic OOP core, so default, static and private interface methods (and lambdas) are shown here as reference code rather than runnable examples. Everything the challenges ask you to write — interfaces, implements, overriding, polymorphism — runs for real.

4

Interface vs Abstract Class

Interface vs abstract class — the decision

Full comparison

AspectInterfaceAbstract class
Keyword to attachimplementsextends
How many per classunlimitedexactly one
Instance fieldsnone (constants only)yes
Constructorsnoneyes
Method bodiesdefault / static / private onlyany concrete method
Member access levelspublic (private only for helpers)public, protected, package-private, private
Relationship expressedCAN-DO (capability)IS-A (family)
Best forunrelated types sharing a capability; swappable implementationsrelated types sharing state and code
Instantiable?nono
Polymorphismyesyes

Rule of thumb: need shared **state** or a protected algorithm → abstract class. Need a capability that unrelated classes can also have, or several capabilities on one class → interface. Combine both when the design calls for it.

Three questions that settle it

  1. Do the subtypes need to share fields? Yes → abstract class.
  2. Might a class need this *and* other unrelated capabilities? Yes → interface.
  3. Is this a real family (SavingsAccount IS-A Account) or just a capability (Account CAN-DO transfer)? Family → abstract class; capability → interface.

Common mistakes

WrongTrying to put instance fields in an interface: `private int speed;`
WhyInterface fields are always `public static final` — constants, not per-object state.
FixKeep state in the implementing class, or use an abstract class.
WrongAssuming a class inherits `static` interface methods.
WhyThey belong to the interface only; `Car.notEmpty()` does not compile.
FixCall them as `Validator.notEmpty()`.
WrongIgnoring a default-method conflict and hoping the compiler picks one.
WhyJava reports *inherits unrelated defaults* and stops.
FixOverride the method in your class and delegate with `A.super.hello()` if needed.

Lesson playground

Free practice

CardPayment signs two contracts; CashPayment signs one. Add a `WalletPayment` that is Payable and Refundable, and refund it too.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

One class, two interfaces, two views. What is printed?

Main.java
1interface Readable2 {
2 void read();
3}
4
5interface Writable2 {
6 void write();
7}
8
9class Notebook implements Readable2, Writable2 {
10 @Override
11 public void read() {
12 System.out.println("Reading notes");
13 }
14
15 @Override
16 public void write() {
17 System.out.println("Writing notes");
18 }
19}
20
21public class Main {
22 public static void main(String[] args) {
23 Notebook notebook = new Notebook();
24
25 Readable2 reader = notebook;
26 Writable2 writer = notebook;
27
28 reader.read();
29 writer.write();
30 }
31}

Summary

  • A class may implement any number of interfaces — safe because interfaces carry no instance state.
  • `default` methods let an interface evolve without breaking existing implementations.
  • `static` interface methods are utilities; `private` ones share code between defaults.
  • Shared state → abstract class; shared capability across unrelated types → interface; often both together.