10.2 Interfaces & Multiple Interface Implementation
Key Takeaways
All fields declared in a Java SE 8 interface are implicitly public, static, and final, and must be initialized at declaration
Ordinary interface methods without default or static are implicitly public and abstract, and cannot be private, protected, or final in Java SE 8
In a class header, extends must appear before implements; a class extends at most one class and implements zero or more interfaces
An interface can extend multiple interfaces using extends, but an interface can never use implements and a class can never extend an interface
A class method implementing an interface instance method must be public. Qualify references to distinct inherited interface fields that have the same name.
Interface Declaration Rules
An interface defines a contract of behaviors, with optional static final fields that unrelated classes can implement regardless of where they sit in the class hierarchy. Because Java allows a class to extend only one superclass, interfaces are Java's mechanism for multiple inheritance of type.
A top-level interface obeys strict declaration rules:
- Visibility: Top-level interfaces may only be
publicor package-private (omitting an access modifier). Marking a top-level interfaceprivateorprotectedfails compilation. - Implicitly
abstract: Every interface is implicitlyabstract. Writingpublic abstract interface Auditableis valid but redundant. - Cannot be
final: Writingfinal interface Auditablefails to compile (illegal modifier for the interface Auditable). - No direct instantiation:
new Auditable()fails to compile unless followed by an anonymous class body{ ... }implementing all unimplemented abstract methods.
Implicit Modifiers in Java SE 8 Interfaces
A huge share of 1Z0-808 interface traps revolve around keywords the compiler inserts automatically when you omit them.
Interface Fields: Implicitly public static final
Every field declared in an interface is implicitly public static final—even if you write no modifiers at all. As a result:
- It is one static final field of the declaring interface. It is a constant variable only if it has primitive or String type and a constant-expression initializer. For example,
int SIZE = Integer.parseInt("3");is a legal field but not a constant variable. - It must be initialized on its declaration line, because interfaces cannot define constructors or initializer blocks (
{}orstatic {}). - It cannot be marked
privateorprotected.
Ordinary Interface Methods: Implicitly public abstract
In Java SE 8, any interface method without default or static is implicitly public abstract and cannot have a body {}. Crucially, Java SE 8 interfaces do not allow private or protected methods (private interface methods were introduced later in Java 9), nor do they allow final on interface methods.
public interface Auditable {
int MAX_RETRIES = 3; // Implicitly public static final
public static final String TAG = "A"; // Explicit modifiers (identical meaning)
void record(String event); // Implicitly public abstract
public abstract String getAuditId(); // Explicit modifiers (identical meaning)
// Compile errors in Java SE 8:
// int UNSET; // Missing initializer for final field
// private int SECRET = 9; // Modifier private not allowed
// protected void check(); // Modifier protected not allowed
// public final void lock(); // Modifier final not allowed
// static { System.out.println(); } // Initializers not allowed in interfaces
}
| Interface Member (Java SE 8) | Implicit Modifiers | Forbidden Modifiers |
|---|---|---|
| Field | public static final | private, protected, transient, volatile |
| Abstract method | public abstract | private, protected, final, static, synchronized |
| Top-level interface | abstract | final, private, protected |
extends vs. implements Syntax
The keywords extends and implements follow strict grammar rules on the 1Z0-808 exam:
- Class extending a class and implementing interfaces:
extendsmust come beforeimplements. A class canextendsat most one class (defaulting tojava.lang.Object) andimplementsa comma-separated list of zero or more interfaces. - Interface extending interfaces: An interface uses
extends(neverimplements) and can extend multiple interfaces separated by commas. - Invalid pairings: A class never
extendsan interface, an interface neverextendsa class, and an interface neverimplementsanother interface.
interface Readable {
void read();
}
interface CloseableResource {
void close();
}
// Valid: an interface extends multiple interfaces
interface Streamable extends Readable, CloseableResource {
void flush();
}
class BaseDevice {
public String deviceId() {
return "DEV-01";
}
}
// Valid: extends appears BEFORE implements
public class FileStream extends BaseDevice implements Streamable {
@Override public void read() { System.out.println("Reading"); }
@Override public void close() { System.out.println("Closing"); }
@Override public void flush() { System.out.println("Flushing"); }
}
// Compile errors:
// class BadOrder implements Readable extends BaseDevice { } // extends must precede implements
// class BadExtends extends Readable { } // class cannot extend an interface
// interface BadImpl implements Readable { } // interface cannot implement an interface
Mandatory public Access in Implementing Classes
One of the most frequent exam traps occurs when an implementing class omits public on an implemented interface method. Remember: in the interface, void read(); is implicitly public. In a class, omitting an access modifier gives package-private access, which is narrower than public.
interface Loggable {
void writeLog(String message); // Implicitly public abstract
}
// Compile error: attempting to assign weaker access privileges; was public
class ConsoleLogger implements Loggable {
void writeLog(String message) {
System.out.println(message);
}
}
To fix ConsoleLogger, you must write public void writeLog(String message). An abstract class implementing Loggable may omit implementing writeLog altogether—leaving it abstract for a concrete subclass—but if it does implement writeLog, that method must still be public.
Important
An abstract class implementing an interface is not required to implement the interface's methods, because the abstract class itself cannot be instantiated. A concrete subclass needs public implementations for the remaining abstract methods, which may be inherited from its superclass.
Constant Ambiguity in Multiple Interface Implementation
What happens when a class implements two interfaces that both declare a constant with the same name? The class declaration itself compiles without error, even if the two fields have different types or values. A use of that simple name is ambiguous when both declarations are in scope. A qualifier that itself inherits both declarations, such as Dashboard.SCALE, is also ambiguous.
interface MetricA {
int SCALE = 10;
}
interface MetricB {
int SCALE = 100;
}
public class Dashboard implements MetricA, MetricB {
public void display() {
// System.out.println(SCALE); // Compile error: reference to SCALE is ambiguous
System.out.println(MetricA.SCALE + " / " + MetricB.SCALE);
}
public static void main(String[] args) {
Dashboard d = new Dashboard();
d.display();
// System.out.println(d.SCALE); // Compile error: reference to SCALE is ambiguous
System.out.println(((MetricB) d).SCALE);
}
}
Output:
10 / 100
100
Because interface fields are static, casting d to (MetricB) resolves SCALE at compile time from the reference type MetricB, printing 100. Whenever you reference a shared constant name inside Dashboard or through a Dashboard reference, qualify it with the interface name (MetricA.SCALE or MetricB.SCALE).
Abstract Classes vs. Java SE 8 Interfaces
| Characteristic | Abstract Class | Java SE 8 Interface |
|---|---|---|
| Multiple inheritance for a class | No (extends at most 1 class) | Yes (implements multiple interfaces) |
| Constructors | Yes | No |
| Instance state (non-static fields) | Yes (any access modifier) | No (all fields are public static final) |
| Abstract method default access | Package-private (unless specified) | Always public |
Can contain private or protected methods | Yes. A protected method may be abstract, but a private one cannot. | No in Java SE 8 |
What is the result of compiling the following Java SE 8 code?
interface Exportable {
int FORMAT_CSV = 1;
void export();
}
public class CsvExporter implements Exportable {
void export() {
System.out.println("CSV: " + FORMAT_CSV);
}
}
Compiles and prints CSV: 1 when export() is called
Compilation fails because FORMAT_CSV is not declared public static final
Compilation fails because export() in CsvExporter reduces visibility from public to package-private
Compilation fails because Exportable is not declared abstract
Assume each option is a top-level declaration and the named types are in scope. Which compiles in Java SE 8?
interface Cacheable extends Serializable, Cloneable { }
class FastList implements List extends AbstractList { }
interface ReadWrite implements Readable, Writable { }
private interface InternalRule { void apply(); }
Given two interfaces interface Low { int LIMIT = 5; } and interface High { int LIMIT = 50; }, and class Range implements Low, High, which statement inside a method of Range compiles in Java SE 8?
System.out.println(LIMIT);
System.out.println(this.LIMIT);
LIMIT = 10;
System.out.println(High.LIMIT);
Sections you finish are checked off in the contents.