Skip to content

Lesson 03 · Interfaces

Objectives

After this lesson you will be able to:

  • Declare interfaces with abstract, default, static, private, and private static methods, and know each member's implicit modifiers.
  • Implement and inherit interfaces (extends between interfaces, implements in a class).
  • Resolve default-method conflicts (the diamond) and the class-wins / most-specific rules.
  • Handle inherited constants and their ambiguity.
  • Identify functional interfaces.
  • Tell an interface from an abstract class.

Interface members and implicit modifiers

An interface is a contract. Its members carry implicit modifiers you don't write:

  • Methods are implicitly public abstract (unless default, static, or private).
  • Fields are implicitly public static final — i.e. constants.
java
interface Shape {
    double PI = 3.14159;            // public static final constant
    double area();                  // public abstract

    default String describe() {     // has a body; instances inherit it
        return label() + area();    // a default may call a private helper
    }
    static Shape unit() { return () -> 1.0; }    // static factory, called Shape.unit()
    private String label() { return "area="; }   // private instance helper (Java 9+)
    private static String tag() { return "shape"; } // private static helper
}
Method kindBody?Implicit accessNotes
abstractnopublicimplementor must override
defaultyespublicinherited by instances; overridable
staticyespubliccalled on the interface, not inherited
private / private staticyesprivatehelpers for the above; not inherited

Exam trap

An interface cannot have instance fields or constructors — its fields are always public static final constants. A default method may not be static, final, or abstract, and no interface method may be protected. A static interface method is not inherited by implementing classes (call it as Shape.unit(), never via an instance).

Implementing and inheriting interfaces

A class implements one or more interfaces and must provide bodies for all inherited abstract methods (an abstract class may leave some unimplemented). An interface can also extends one or more other interfaces — multiple inheritance of type.

java
interface A { void a(); }
interface B { void b(); }
interface AB extends A, B { }        // an interface may extend several interfaces

class Impl implements AB {            // must implement BOTH a() and b()
    public void a() { }
    public void b() { }
}

Gotcha

A class can implements many interfaces but extends only one class. An implementing class must satisfy every abstract method inherited through the whole interface hierarchy, not just the directly named interface.

The diamond problem & resolution rules

If a class inherits two default methods with the same signature, the compiler can't choose — the class must override to resolve it, optionally delegating with Interface.super.method().

java
interface IA { default String hi() { return "A"; } }
interface IB { default String hi() { return "B"; } }
class C implements IA, IB {
    @Override public String hi() {
        return IA.super.hi() + IB.super.hi();   // explicit choice → "AB"
    }
}

Two rules decide automatically when there's no tie:

  • Class wins: a method declared (or inherited) by a class always beats an interface default.
  • Most-specific wins: a default in a sub-interface overrides the one in its super-interface, so no conflict arises.
java
interface Base { default String tag() { return "base"; } }
interface Refined extends Base { default String tag() { return "refined"; } }
class R implements Refined { }
new R().tag();   // "refined" — the more specific interface wins

Constants and ambiguity

Interface fields are inherited as constants. If a class inherits two same-named constants from unrelated interfaces, an unqualified reference is ambiguous — qualify it with the interface name.

java
interface X { int VALUE = 1; }
interface Y { int VALUE = 2; }
class Z implements X, Y {
    int pick() { return X.VALUE; }   // must qualify; bare VALUE would not compile
}

Functional interfaces

A functional interface has exactly one abstract method (a SAM — Single Abstract Method), so it can be implemented by a lambda or method reference. default, static, and private methods don't count toward the one; @FunctionalInterface makes the compiler enforce the rule.

java
@FunctionalInterface
interface Greeter {
    String greet(String name);          // the single abstract method
    default String shout(String n) { return greet(n).toUpperCase(); }  // doesn't count
}

Greeter g = name -> "hi " + name;       // a lambda IS the implementation
g.greet("sam");                          // "hi sam"

Beyond the exam

You only need to identify functional interfaces for the 1Z0-830 here; the full lambda and java.util.function toolkit (Function, Predicate, method references, composition) lives in Module 06. Note that Runnable, Comparator, and Callable are all functional interfaces.

Interface vs abstract class

InterfaceAbstract class
Multiple inheritanceYes (implements many)No (extends one)
Instance fieldsNo (constants only)Yes
ConstructorsNoYes
Method bodiesdefault/static/privateany non-abstract method
Statenoneyes

Choose an interface for a capability many unrelated types can have; an abstract class when subclasses share state and a common base.

SDET note

Test doubles lean on interfaces: a default method conflict or a missing implementation surfaces at compile time, and a one-method (functional) interface is trivial to fake with a lambda — no mocking framework needed.

Key Takeaways

  • Interface methods are implicitly public abstract; fields are public static final constants. No instance fields, no constructors. static interface methods are not inherited.
  • Bodies come via default, static, private, or private static methods; defaults can't be static/final/abstract.
  • A class implements many interfaces; an interface extends many interfaces. Implementors must satisfy every inherited abstract method.
  • Conflicting defaults must be overridden (Iface.super.m()); otherwise class wins and the most-specific interface wins. Ambiguous inherited constants must be qualified.
  • A functional interface has exactly one abstract method (SAM) and can be a lambda; @FunctionalInterface enforces it.
  • Prefer an interface for a shared capability, an abstract class for shared state + base.

Lesson Quiz

Lesson Quiz · Interfaces0 / 9
  1. What are the implicit modifiers on int MAX = 10; in an interface?

    • Apublic abstract
    • Bpublic static final
    • Cprivate final
    • Dprotected static
  2. Two implemented interfaces both declare default String hi(). What must class C do?

    • ANothing — picks one at random
    • BOverride hi() to resolve the conflict
    • CIt won't compile no matter what
    • DMark C abstract
  3. What does new R().tag() return?

    interface Base { default String tag(){return "base";} }
    interface Refined extends Base { default String tag(){return "refined";} }
    class R implements Refined {}
    • Abase
    • Brefined
    • CCompile error — conflict
    • Dbaserefined
  4. Why does return VALUE; not compile in class Z?

    interface X { int VALUE = 1; }
    interface Y { int VALUE = 2; }
    class Z implements X, Y { int pick(){ return VALUE; } }
    • AConstants can't be inherited
    • BVALUE is ambiguous — inherited from both X and Y; qualify it (X.VALUE)
    • CVALUE isn't final
    • DZ must be abstract
  5. Which is ILLEGAL in an interface?

    • Adefault method
    • Bprivate static method
    • Can instance field
    • Dstatic method
  6. Which interface is a functional interface?

    • AOne with two abstract methods
    • BOne with exactly one abstract method (plus any default/static methods)
    • CAny interface annotated public
    • DOne with only constants
  7. How do you call a static method parse() declared in interface Codec?

    • Anew Codec().parse()
    • BCodec.parse()
    • Cthis.parse()
    • Dsuper.parse()
  8. How many classes can a class extend, and how many interfaces implement?

    • A1 class, 1 interface
    • Bmany classes, 1 interface
    • C1 class, many interfaces
    • Dmany of each
  9. Can an interface declare a constructor or an instance field?

    • ABoth
    • BConstructor only
    • CInstance field only
    • DNeither

Next: Enums. Run the matching code in labs/src/main/java/com/jse21/m03_oop/.