Java Interfaces: Declaring and Implementing Interfaces
Learn Java interfaces from the ground up: interfaces as contracts, implementing Comparable to sort objects, the compareTo rules and pitfalls with doubles, interface variables and instanceof, extending interfaces, constants, multiple interfaces, and interfaces versus abstract classes.
kvi5hnuCode Sprout team member12 min readOn this page
Classes and inheritance let you model things. Part 6 adds the tools that let pieces of code cooperate without knowing each other's classes:
- Interfaces state a contract, which methods a type offers, without fixing an implementation. A class may implement any number of them.
- Lambda expressions package a piece of behavior as a value that can be passed around and run later.
- Inner classes live inside another class and can use its fields, which suits small helper objects that belong to one class.
- Service loaders and proxies support plug-in architectures and generated implementations.
We start with interfaces.
The Interface Concept
An interface is not a class but a contract: a list of methods that any implementing class promises to provide.
Interfaces typically show up where a library offers a service that needs a little cooperation from your objects. Arrays.sort, for example, can sort an array of your objects provided it can ask any two of them which comes first. It asks through the Comparable interface, which is tiny:
public interface Comparable<T> {
int compareTo(T other); // parameter has type T
}
compareTo has no body here; it is abstract. A class declaring implements Comparable<Employee> takes on the obligation to define int compareTo(Employee other). If it doesn't, the class must be declared abstract and can't be instantiated.
![Arrays.sort is a service that needs the Comparable interface, and Employee fulfils it by implementing Comparable<Employee>; inside sort, the call a[i].compareTo(a[j]) compiles because every Comparable has compareTo](https://code-sprout-content.laxmi.solutions/asset/2026/11/fn5jmbz3mujumkkz.png)
A few rules about interface methods:
- All abstract methods in an interface are automatically
public, so you don't writepublicwhen declaring them. (The only exception is theprivatehelper methods of the next article.) - Part of the contract lives only in the documentation:
x.compareTo(y)returns a negative value whenxshould come beforey, zero when they rank the same, and a positive value whenxcomes after. - Interfaces can define constants, but they never have instance fields. Since Java 8, interfaces may also contain methods with bodies (
defaultandstaticmethods, plusprivatemethods since Java 9), which are covered in the next article. Those methods can't refer to instance fields either, because interfaces don't have any.
Implementing an Interface
To make a class implement an interface, you do two things:
- Declare that the class intends to implement the interface, with the
implementskeyword. - Supply definitions for all methods of the interface.
class Employee implements Comparable<Employee> {
. . .
public int compareTo(Employee other) {
return Double.compare(salary, other.salary);
}
}
Double.compare(a, b) already follows the negative/zero/positive convention, so it can be returned directly. Thanks to the type argument, the parameter is an Employee; with the raw Comparable it would be an Object that you'd have to cast.
Choosing the comparison
compareTo only needs to return some negative or positive value, not specifically -1 or 1. That's tempting for integer fields: to sort by a unique int id, you might write return id - other.id;. It works only if the subtraction can't overflow. With id values near the extremes of int, the difference wraps around and has the wrong sign. The demo below shows 2_000_000_000 - (-2_000_000_000) coming out negative. You're safe if the IDs are non-negative, or their absolute value is at most (Integer.MAX_VALUE - 1) / 2. Otherwise, and as a habit, call Integer.compare(id, other.id).
The subtraction trick never works for floating-point values: salary - other.salary can round to 0 for close but different salaries, and converting a double to an int loses the sign of small differences. Use Double.compare.
Doubles: operators versus Double.compare
There are subtle differences between the relational operators on double and the Double methods:
| Expression | Result | Why |
|---|---|---|
-0.0 == 0.0 | true | Operators treat the zeros as equal |
Double.compare(-0.0, 0.0) | -1 | Double orders -0.0 before 0.0 |
Double.NaN == Double.NaN | false | Every comparison with NaN is false |
Double.compare(Double.NaN, Double.NaN) | 0 | Double treats NaN as equal to itself |
Double.compare(Double.NaN, Double.POSITIVE_INFINITY) | 1 | NaN is ordered above infinity |
Double.valueOf(-0.0).equals(Double.valueOf(0.0)) is false and Double.valueOf(Double.NaN).equals(Double.valueOf(Double.NaN)) is true, consistent with Double.compare. This gives a total order that sorting needs. The generated equals of a record with double components uses the same logic.
Consistency with equals
The Comparable documentation recommends that compareTo be consistent with equals: x.compareTo(y) == 0 exactly when x.equals(y). Most JDK classes follow it, with notable exceptions:
BigDecimal:new BigDecimal("2.5").equals(new BigDecimal("2.50"))isfalse, sinceequalsalso compares the scale, whilecompareToreports them as numerically equal.StringBuilderimplementsComparable(since Java 11) but doesn't overrideequals, so two builders with the same content arecompareTo-equal but notequals.
This has visible effects: a TreeSet<BigDecimal> keeps only one of 2.5 and 2.50, while a HashSet keeps both.
The compareTo contract and inheritance
The language specification requires that sgn(x.compareTo(y)) = -sgn(y.compareTo(x)) for all x and y. In plain English: if you flip the arguments, the sign of the result must flip too. (That also means x.compareTo(y) must throw an exception exactly when y.compareTo(x) does.)
Subclasses make this tricky, just as with equals. Manager inherits Comparable<Employee>, so an override in Manager receives arbitrary employees, not just managers. Casting the argument is a trap:
class Manager extends Employee {
public int compareTo(Employee other) {
Manager otherManager = (Manager) other; // NO
. . .
}
}
That breaks antisymmetry: employee.compareTo(manager) compares them as employees, but manager.compareTo(employee) throws a ClassCastException. The remedies mirror those for equals:
- If subclasses have different notions of comparison, outlaw comparing objects of different classes. Each
compareTostarts withif (getClass() != other.getClass()) throw new ClassCastException();. - If one ordering fits the whole hierarchy, implement
compareToonce in the superclass and declare itfinal. Subclass-specific information can still feed into it through an overridable method, say aseniorityLevel()that the singlecompareTochecks before salary.
Why Interfaces?
Why can't Employee just provide a compareTo method without declaring implements Comparable? Because Java is strongly typed. Somewhere inside sort there are statements like
if (a[i].compareTo(a[j]) > 0) {
// rearrange a[i] and a[j]
. . .
}
The compiler must know that a[i] has a compareTo method. If a is an array of Comparable objects, that's guaranteed, because every class that implements Comparable must supply the method.
Here's the complete sorting program, plus the other facts from this article:
import java.math.BigDecimal;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
var staff = new Employee[3];
staff[0] = new Employee("Omar Haddad", 35000);
staff[1] = new Employee("Priya Nair", 68000);
staff[2] = new Employee("Lena Fischer", 38000);
Arrays.sort(staff); // works because Employee implements Comparable<Employee>
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
// interface variables and instanceof
Comparable<Employee> x = staff[0];
System.out.println(x.compareTo(staff[1]) < 0);
Object any = staff[0];
System.out.println(any instanceof Comparable<?> + " " + (any instanceof Cloneable));
// the subtraction trick overflows for large values
int a = 2_000_000_000, b = -2_000_000_000;
System.out.println((a - b) + " vs " + Integer.compare(a, b));
// double comparisons: operators vs Double.compare
System.out.println((-0.0 == 0.0) + " " + Double.compare(-0.0, 0.0));
System.out.println((Double.NaN == Double.NaN) + " " + Double.compare(Double.NaN, Double.NaN)
+ " " + Double.compare(Double.NaN, Double.POSITIVE_INFINITY));
// compareTo not consistent with equals
var d1 = new BigDecimal("2.5");
var d2 = new BigDecimal("2.50");
System.out.println(d1.equals(d2) + " " + d1.compareTo(d2));
var sb1 = new StringBuilder("Hello");
var sb2 = new StringBuilder("Hello");
System.out.println(sb1.equals(sb2) + " " + sb1.compareTo(sb2));
// interface hierarchy, constants, multiple interfaces
Recordable rec = new VoiceRecorder(90, 25);
rec.play(30);
Playable p = rec; // a Recordable is a Playable
System.out.println(rec.freeMinutes() + " min free, " + Recordable.SAMPLE_RATE + " Hz " + (p == rec));
// program to the CharSequence interface
System.out.println(countVowels("Interfaces") + " " + countVowels(new StringBuilder("lambda")));
}
static int countVowels(CharSequence s) {
int count = 0;
for (int i = 0; i < s.length(); i++)
if ("aeiouAEIOU".indexOf(s.charAt(i)) >= 0) count++;
return count;
}
}
class Employee implements Comparable<Employee> {
private final String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() { return name; }
public double getSalary() { return salary; }
public void giveRaise(double pct) {
double raise = salary * pct / 100;
salary += raise;
}
// orders employees from lowest to highest salary
@Override
public int compareTo(Employee other) {
return Double.compare(salary, other.salary);
}
}
interface Playable {
void play(int seconds);
}
interface Recordable extends Playable {
int freeMinutes();
int SAMPLE_RATE = 48_000; // a public static final constant
}
class VoiceRecorder implements Recordable {
private final int capacityMinutes;
private final int recordedMinutes;
private int playedSeconds;
VoiceRecorder(int capacityMinutes, int recordedMinutes) {
this.capacityMinutes = capacityMinutes;
this.recordedMinutes = recordedMinutes;
}
@Override public void play(int seconds) { playedSeconds += seconds; }
@Override public int freeMinutes() { return capacityMinutes - recordedMinutes; }
}
name=Omar Haddad,salary=35000.0
name=Lena Fischer,salary=38000.0
name=Priya Nair,salary=68000.0
true
true false
-294967296 vs 1
true -1
false 0 1
false 0
false 0
65 min free, 48000 Hz true
4 2
Properties of Interfaces
Interfaces aren't classes. You can never use new to instantiate one:
x = new Comparable(. . .); // ERROR
But you can declare interface variables, which must refer to objects of classes that implement the interface:
Comparable<Employee> x = new Employee(. . .); // OK provided Employee implements Comparable
instanceof works with interfaces, just as with classes:
if (anObject instanceof Comparable<?> c) { . . . }
Interfaces can extend other interfaces, forming chains from more general to more specialized:
public interface Playable {
void play(int seconds);
}
public interface Recordable extends Playable {
int freeMinutes();
int SAMPLE_RATE = 48_000; // a public static final constant
}
A class that implements Recordable must supply both play and freeMinutes, and its objects can be used wherever a Playable is expected.
Interfaces can contain constants, not instance fields. Just as methods in an interface are automatically public, fields are automatically public static final. You may write those modifiers explicitly, and some programmers do out of habit or for clarity, but the Java Language Specification recommends leaving the redundant keywords out.
A class can implement multiple interfaces. While each class has only one superclass, it can implement as many interfaces as it likes, separated by commas. For example, the Cloneable interface (covered in the cloning article) tells Object.clone that copying is allowed. If you want both cloneability and comparability, implement both:
class Employee implements Cloneable, Comparable<Employee>

Records and enums can't extend classes (they implicitly extend Record and Enum), but they can implement interfaces. And interfaces can be sealed: the direct subtypes, classes or interfaces, must then be listed in a permits clause or be in the same source file (see sealed classes).
Interfaces and Abstract Classes
If you've read about abstract classes, you may wonder why Java has interfaces at all. Why can't Comparable be an abstract class?
abstract class Comparable { // why not?
public abstract int compareTo(Object other);
}
class Employee extends Comparable { // why not?
public int compareTo(Object other) { . . . }
}
Because a class can extend only one class. If Employee already extends Person, it can't extend a second class:
class Employee extends Person, Comparable // ERROR
But it can implement as many interfaces as it likes:
class Employee extends Person implements Comparable<Employee> // OK
Some languages, C++ among them, allow several superclasses (multiple inheritance of classes). Java deliberately doesn't: when two superclasses both contribute fields and constructors, questions such as "which copy of a shared ancestor's field does the object get?" need complicated rules. Interfaces carry no instance state, so a class can implement many of them without those problems.
Program to interfaces
You've already used an interface in this course: CharSequence, implemented by String, StringBuilder, StringBuffer and a few more. It has the operations common to all sequences of characters: length, charAt, subSequence, chars/codePoints, isEmpty (Java 15) and the static CharSequence.compare (Java 11). The interface is rather small, but if those operations are enough for your task, accept a CharSequence instead of a String. Then your method works with strings, string builders and other character sequences, like countVowels in the demo.
That's a general principle: declare parameters and variables with the most general interface that offers what you need (List rather than ArrayList, CharSequence rather than String, Comparable<T> rather than a concrete class). Callers get flexibility, and you can change implementations freely.
Common questions
Can an interface have a constructor or instance fields?
No. Interfaces have no state, so they have nothing to construct. They can have constants (public static final), static methods, and default and private methods. Shared state belongs in an abstract class or in the implementing classes.
Why must I write public when implementing an interface method?
Interface methods are implicitly public, and an implementation can't reduce visibility. A method without a modifier in a class has package access, which is weaker, so the compiler rejects it.
Should I sort with Comparable or Comparator?
Implement Comparable for a class's single natural order, such as numbers by value or dates chronologically. Use a Comparator for every other order (by length, by name, descending), and for classes you can't modify. Modern code builds comparators with Comparator.comparing(...).thenComparing(...).
Is return a - b; OK in compareTo?
Only when the subtraction can't overflow. Use Integer.compare(a, b), Long.compare or Double.compare, which are always correct and just as fast. Subtracting double values is never correct, because small differences may round or truncate to zero.
Can an interface extend a class? No. An interface can extend only other interfaces, as many as it likes. A class can extend one class and implement many interfaces.
Summary
- An interface is a set of requirements: abstract methods (automatically
public), plus constants (automaticallypublic static final). It has no instance fields. - A class implements an interface by declaring
implementsand supplyingpublicimplementations of all its methods. Comparable<T>letsArrays.sortand sorted collections order your objects. UseInteger.compare/Double.compareinstead of subtraction, keepcompareToantisymmetric, and preferably consistent withequals.- You can't instantiate interfaces, but you can declare interface variables, test with
instanceof, and extend interfaces with other interfaces. - A class has one superclass but can implement many interfaces, which is why interfaces, not abstract classes, express general capabilities.
- Records and enums can implement interfaces, and interfaces can be sealed.
Practice Questions
Your class declares int compareTo(Employee other) without public and fails to compile. Why?
Interface methods are implicitly public. Omitting public in the class gives the method package access, which is weaker than the interface requires, so the compiler rejects it.
Why is return this.id - other.id; risky in compareTo, and what should you write?
The subtraction can overflow for large positive and negative values, producing the wrong sign. Use Integer.compare(this.id, other.id).
What do -0.0 == 0.0 and Double.compare(-0.0, 0.0) return?
true and -1. The operator treats the zeros as equal, while Double.compare orders -0.0 before 0.0.
You put new BigDecimal("2.0") and new BigDecimal("2.00") into a TreeSet and a HashSet. What are the sizes?
The TreeSet has size 1, because it uses compareTo, which returns 0. The HashSet has size 2, because it uses equals and hashCode, which consider the scale.
Which declarations are legal? Comparable c; c = new Comparable(); interface A extends B, C {} class D implements A, B {}
Comparable c; is legal. new Comparable() is illegal, since interfaces can't be instantiated. An interface may extend several interfaces, and a class may implement several, so the last two are legal (given that A, B and C are interfaces).
Why isn't Comparable an abstract class?
A class can extend only one class. If Comparable were a class, any class that already has a superclass, such as Employee extends Person, couldn't be comparable. Interfaces can be implemented in any number.
Previous: Java Inheritance Design Hints: Best Practices for Class Hierarchies
Related reading
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Type Erasure: Raw Types, Translation and Bridge Methods
- Bounded Type Parameters in Java Generics: extends and Multiple Bounds
- Java Generics: Generic Classes and Generic Methods
- Java Debugging Tips: Practical Techniques Beyond the Debugger

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.