Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
Java interfaces for the OCP 21 exam: declaring and implementing them, implicit modifiers on constants and abstract methods, extending multiple interfaces, duplicate abstract methods, class versus interface keywords, plus the @Deprecated, @SuppressWarnings and @SafeVarargs annotations.
kvi5hnuCode Sprout team member7 min readOn this page
Chapter 7 moves beyond classes to the other kinds of type Java offers: interfaces, enums, sealed types, records and nested classes. Remember the file rules from chapter 1. A source file may have at most one public top-level type, and its name must match the file name. A top-level type can only be public or package access.
This article covers interfaces with abstract methods and constants. The next one adds default, static and private methods.
What an interface is
An interface declares a set of methods that implementing classes promise to provide. A class can extend only one class, but it can implement any number of interfaces:
public interface Rechargeable {
int FULL = 100; // a constant
void charge(int minutes); // an abstract method
}
public class Drone implements Rechargeable, Comparable<Drone> {
private int battery;
@Override public void charge(int minutes) { battery = Math.min(FULL, battery + minutes * 2); }
@Override public int compareTo(Drone o) { return Integer.compare(battery, o.battery); }
}
Implementing an interface method is overriding, so all the rules from article 34 apply. An interface can't be instantiated (new Rechargeable() doesn't compile), but it's a full type. You can declare variables, parameters and lists of it, and use it with instanceof.
Implicit modifiers
Interfaces are full of modifiers that the compiler adds for you:
| Member | Implicit modifiers |
|---|---|
| the interface itself | abstract |
| a field (constant) | public static final |
a method without a body (and not private) | public abstract |
any method without private | public |

You may write these modifiers yourself, so public abstract interface Rechargeable and public static final int FULL = 100; both compile. You can't write a modifier that conflicts with them:
interface Pump {
private int RATE = 4; // DOES NOT COMPILE: modifier private not allowed here
protected void prime(); // DOES NOT COMPILE: modifier protected not allowed here
final void stop(); // DOES NOT COMPILE: abstract methods can't be final
int LIMIT; // DOES NOT COMPILE: a constant needs a value (= expected)
}
final interface Sealed { } // DOES NOT COMPILE: illegal combination of modifiers: interface and final
Consequences you'll see on the exam:
- Constants can't be reassigned.
LIMIT = 5;in an implementing class fails with "cannot assign a value to static final variable". Constants can be read asRechargeable.FULL, asDrone.FULL, or as plainFULLinside an implementing class. - An implementing class must declare the methods
public. Leaving out the modifier means package access, which is weaker thanpublic:
abstract class Toy { abstract void play(); } // package access
interface Game { void play(); } // implicitly public
class Ball implements Game { void play() { } } // DOES NOT COMPILE: weaker access privileges; was public
class Kite extends Toy { void play() { } } // compiles: matches package access
- Interfaces have no constructors, no instance or static initializer blocks ("initializers not allowed in interfaces") and no instance fields. They aren't part of object initialization (article 33).
- No interface member can be
protectedor package access. Members are eitherpublicor, for methods only,private(next article).
Extending interfaces
An interface can extend other interfaces, as many as it likes:
interface Swimmer { void swim(); }
interface Diver { int maxDepth(); }
interface Snorkeler extends Swimmer, Diver { }
class Otter implements Snorkeler {
public void swim() { }
public int maxDepth() { return 15; } // must implement all three interfaces' abstract methods
}
Get the keywords right, because the exam mixes them up on purpose:
| Declaration | Keyword | Count |
|---|---|---|
| class → class | extends | one |
| class → interface | implements | many |
| interface → interface | extends | many |
| interface → class | (impossible) | — |
interface Charger { }
class Phone extends Charger { } // DOES NOT COMPILE: no interface expected here
class Cable { }
interface Wireless extends Cable { } // DOES NOT COMPILE: interface expected here
interface Fast implements Charger { } // DOES NOT COMPILE: interfaces never "implement"
A class can extend and implement at the same time, but extends must come first: class Drone extends Machine implements Flyer, Camera.
Inheriting abstract methods
The first concrete class rule from article 35 still applies. Abstract classes may leave interface methods unimplemented, and the first concrete class must implement every abstract method it inherits from any class or interface above it:
interface Screen { int inches(); }
interface Battery { int hours(); }
abstract class Tablet implements Screen, Battery { } // fine: abstract
class KidsTablet extends Tablet { } // DOES NOT COMPILE: owes both methods
Duplicate abstract methods
Two interfaces can declare the same method. A class implementing both needs one method that correctly overrides both:
interface Grazer { int eat(int grass); }
interface Forager { int eat(int food); } // parameter names don't matter
class Goat implements Grazer, Forager {
public int eat(int amount) { return amount - 1; } // satisfies both
}
If the return types differ, the single method must be covariant with both:
interface Meter { Number reading(); }
interface Thermometer { Double reading(); }
class Thermostat implements Meter, Thermometer {
public Double reading() { return 21.5; } // OK: Double works for both
// public Number reading() would fail: Number isn't compatible with Double
}
If no such method is possible, for example with void eat(int) and int eat(int), then any class implementing both interfaces fails to compile, abstract classes included: "types Forager and Grazer are incompatible; both define eat(int), but with unrelated return types". The class body makes no difference.
If the parameter lists differ, the methods are simply overloads, and the class must implement each one.
Interfaces and instanceof
Because any non-final class could have a subclass that implements an interface, the compiler allows instanceof and casts from a class type to an unrelated interface:
interface Flyer { }
class Rock { }
final class Pebble { }
Rock r = new Rock();
boolean b1 = r instanceof Flyer; // compiles (false at run time)
Pebble p = new Pebble();
boolean b2 = p instanceof Flyer; // DOES NOT COMPILE: a final Pebble can never be a Flyer
Article 45 explores casting in depth. An interface reference can still call the public Object methods, such as toString(), equals() and hashCode(), because every implementing object is an Object. An interface can't declare a default version of those methods.
Annotations to know
Annotations are metadata tags on declarations. Besides @Override and @FunctionalInterface (chapter 8), the exam expects you to recognize three of them:
@Deprecated marks an API that shouldn't be used. It has optional elements: @Deprecated(since = "3.0", forRemoval = true). Using a deprecated member from another class causes a compiler warning. With forRemoval = true, javac always prints a [removal] warning. A plain deprecation shows only a "Note" unless you compile with -Xlint:deprecation.
@SuppressWarnings turns off named warnings for the annotated declaration. Common names are "deprecation", "removal", "unchecked" and "rawtypes". You can pass a single string or an array: @SuppressWarnings({"deprecation", "removal"}). Each warning kind needs its own name, so "deprecation" doesn't silence [removal] warnings.
@SafeVarargs promises that a method doesn't do anything unsafe with a generic varargs parameter such as List<String>.... That silences the "possible heap pollution" warning. It's allowed only on methods that can't be overridden (static, final or private methods, and constructors), and only if they really are varargs:
@SafeVarargs static void merge(List<String>... parts) { } // OK
@SafeVarargs final void addAll(List<String>... parts) { } // OK
@SafeVarargs void broken(List<String>... parts) { } // DOES NOT COMPILE: neither final nor private
@SafeVarargs static void notVarargs(int x) { } // DOES NOT COMPILE: not a varargs method
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Since Java 8 interfaces can have
defaultandstaticmethods, and since Java 9privateones (article 38). Interfaces still can't have instance fields or constructors.
Exam traps from this article
A complete example
The program builds a small device hierarchy: two interfaces related by extends, an abstract class that implements some methods, a concrete class that finishes the job, and one method that satisfies two duplicate interface declarations.
import java.util.List;
public class Solution {
interface Switchable {
int MAX_LEVEL = 10; // implicitly public static final
void turnOn(); // implicitly public abstract
boolean isOn();
}
interface Dimmable extends Switchable { // an interface extends interfaces
void setLevel(int level);
}
interface Meter { Number reading(); }
interface Thermometer { Double reading(); } // compatible duplicate: Double is a Number
// Abstract class may leave interface methods unimplemented
abstract static class Appliance implements Switchable {
private boolean on;
@Override public void turnOn() { on = true; } // must be public
@Override public boolean isOn() { return on; }
}
// First concrete class: owes setLevel() from Dimmable
static class SmartBulb extends Appliance implements Dimmable {
private int level;
@Override public void setLevel(int level) {
this.level = Math.min(level, MAX_LEVEL); // constant inherited from Switchable
}
@Override public String toString() { return "SmartBulb(level " + level + ", on " + isOn() + ")"; }
}
// One method satisfies both reading() declarations
static class Thermostat extends Appliance implements Meter, Thermometer {
@Override public Double reading() { return 21.5; }
@Override public String toString() { return "Thermostat(on " + isOn() + ")"; }
}
public static void main(String[] args) {
SmartBulb bulb = new SmartBulb();
bulb.setLevel(14);
Thermostat thermo = new Thermostat();
List<Switchable> devices = List.of(bulb, thermo); // interface as a type
for (Switchable s : devices) {
s.turnOn();
System.out.println(s);
}
Meter m = thermo;
Thermometer t = thermo;
Number n = m.reading();
Double d = t.reading();
System.out.println("Meter sees " + n + ", Thermometer sees " + d);
System.out.println("Switchable.MAX_LEVEL = " + Switchable.MAX_LEVEL
+ ", via SmartBulb: " + SmartBulb.MAX_LEVEL);
System.out.println("bulb is Dimmable: " + (bulb instanceof Dimmable)
+ ", thermo is Dimmable: " + (devices.get(1) instanceof Dimmable));
System.out.println("Switchable is an interface: " + Switchable.class.isInterface());
}
}
Output:
SmartBulb(level 10, on true)
Thermostat(on true)
Meter sees 21.5, Thermometer sees 21.5
Switchable.MAX_LEVEL = 10, via SmartBulb: 10
bulb is Dimmable: true, thermo is Dimmable: false
Switchable is an interface: true
Points to notice:
Applianceis abstract and implements bothSwitchablemethods.SmartBulbonly owessetLevel()fromDimmable.- Every implementing method is
public, even though the interfaces never write it. MAX_LEVELis readable asSwitchable.MAX_LEVEL, asSmartBulb.MAX_LEVEL, or unqualified insideSmartBulb.Thermostat.reading()returnsDouble, which overridesNumber reading()andDouble reading()at the same time.- The list is typed as
List<Switchable>. Interfaces are types, even though they can't be instantiated.
Common questions
Why do interfaces allow multiple inheritance but classes don't? Classes carry state and constructors, so inheriting from two classes would raise questions about which fields and initialization to use. Abstract methods carry no implementation, so there's nothing to conflict. Default methods do bring in behavior, and the next article covers their conflict rules.
Are interface constants a good idea? They're useful for genuinely shared values. Implementing an interface just to get short names for its constants (the "constant interface" pattern) is considered poor style. A static import is the better tool for that.
Is @Override required when implementing interface methods?
No, but it's recommended. It catches typos and signature mismatches at compile time.
Summary
- Interfaces declare constants (
public static final) and methods (abstract ones are implicitlypublic abstract). The interface itself is implicitlyabstract. - Classes
implementsany number of interfaces. Interfacesextendsany number of interfaces. - Implementations must be
publicand follow every overriding rule. The first concrete class implements every inherited abstract method. - Duplicate abstract methods are fine if one method can override them all. Otherwise no class can implement both interfaces.
@Deprecatedwarns callers,@SuppressWarningssilences named warnings, and@SafeVarargsmarks safe generic varargs on non-overridable methods.
Practice quiz
Test yourself with the interfaces quiz: 10 exam-style questions with explanations.
Previous: Java Immutable Objects and Defensive Copies (OCP 21)
Next: Java Interface default, static and private Methods (OCP 21)
Related reading
- Java Abstract Classes and Abstract Methods (OCP 21)
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
- Java while, do/while, for and for-each Loops (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.