The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Java
Interfaces
What does an interface look like in code, and what does it decide?
Why it exists — If the code that uses a feature is tied to one particular class name, then every time you change that feature to work another way, the code on the using side has to be changed too. An interface fixes "these methods exist" as a type, so the using side calls methods by looking only at that type, and it can handle an object of any class that actually arrives with the same code. A class can inherit from only one class with extends, but it can implement several interfaces with implements, so classes that have nothing to do with each other can still be of the same interface type.
Where it's used today — Java's List and Map are interfaces, so as in List<String> names = new ArrayList<>(); you write the variable with the interface type and choose between ArrayList and LinkedList to create the actual object. If a class you wrote implements Java's Comparable, Collections.sort can sort a list of that class, and if it implements Runnable, it becomes the work that a thread runs. In Spring Data JPA, if you only declare an interface that extends JpaRepository, Spring creates the object that implements it for you.
An interface is a type that you declare with interface, and it fixes "if something is of this type, it has these methods". The interfaces you meet most often are the ones that Java provides. List, which handles lists, is an interface in the java.util package, and ArrayList and LinkedList are classes that implement it with implements List. Comparable, which decides sort order, is also an interface that Java provides, and Collections.sort sorts a list of elements that implement Comparable. In this lab you compile and run short programs that use Java's List and Comparable, change the type of a variable and the object that is created, or delete implements, and see what the compiler reports and what is printed. At the end you briefly see what it looks like to declare an interface yourself, and how it differs from inheriting a class with extends.
Checked against real execution · Seventeen combinations of the code on the screen (12 for the List list, 3 for Comparable sorting, 2 for declaring an interface yourself) were compiled with javax.tools and run on JDK 21 and checked against the model, and the declarations of List, ArrayList, LinkedList, Comparable, and Collections.sort were checked by reflection
Concepts in this lab
- Interface
- This is a type that defines the list of methods (the contract) that a class must implement. It cannot have instance variables, and one class can implement several of them. If the calling code depends only on this type, it is easy to change the implementing class or to replace it with a fake implementation for testing.
- List, Set, Map
- These are the three basic kinds of Java collections. A List is ordered, allows duplicates, and is accessed by index. A Set does not allow duplicates. A Map stores key-value pairs, and its keys cannot be duplicated. You choose among them by the nature of the data (whether order is needed, whether duplicates are allowed, and whether you look things up by key).
- ArrayList
- This is a list that refers to an array through a field, and when that array is full, it creates a larger array and copies the elements over. Access to an element by index is fast at O(1), and adding at the end is also O(1) amortized. Inserting or removing in the middle takes O(n), because the elements after that position must each be shifted by one position.
- LinkedList
- Where it's used today — You choose it when you often insert and remove middle elements while iterating with ListIterator's add and remove, or when you need a queue that must also hold null (ArrayDeque does not accept null). For other lists and queues, ArrayList and ArrayDeque are usually enough.
- This is a list in which each element (node) is linked by pointing to the locations of the elements before and after it. If the position is already known, insertion and removal are O(1), but finding the nth element is O(n) because you must follow the links from the start. Each node needs extra memory and the nodes are scattered in memory, so real traversal performance is often worse than that of an array-based list.
- Comparable and Comparator
- These are the two ways to define the order of objects. Comparable is an interface that a class implements itself, and its single method, compareTo, defines the natural ordering of that class. A Comparator is a way of comparing that is created separately, outside the class, and it lets you sort the same objects by a different sort key each time. Both return a negative number if the first object comes first, 0 if the order cannot be decided, and a positive number if it comes later. Returning the difference of two numbers as it is can flip the sign through overflow, so use Integer.compare or Comparator.comparingInt.
- Collections.sort
- Where it's used today — Use it to sort a list in the default order of its class, such as by name or by age. These days, code that calls the sort method of List directly, such as list.sort(null) or list.sort(Comparator.comparing(...)), is also common.
- Collections.sort is a sort method that Java puts in java.util.Collections. It takes a list (List) and puts its elements back in order. The declaration of Collections.sort(list) is public static <T extends Comparable<? super T>> void sort(List<T> list), and you can call it only when the element type implements Comparable. While sorting, it calls compareTo of the elements to decide which of two elements comes first. Java has already made String and Integer implement Comparable, so they are sorted right away, and a class you wrote has to write implements Comparable and compareTo. If it does not, you get the compile-time error no suitable method found for sort. Collections.sort(list, comparator), which passes a Comparator along with the list, can be used even when the elements are not Comparable. It is a stable sort that keeps the original order of equal values.
- implements
- Where it's used today — Use it when you make a class that follows an interface that Java provides. For example, if a class you wrote implements Comparable, Collections.sort can sort a list of that class, and if it implements Runnable, you can write the work for a thread to run.
- implements is the keyword in a class declaration that says which interface the class implements. You write it after the class name, as in Java's ArrayList, which is declared as class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable. After extends you can write only one class, but after implements you can write several interfaces separated by commas. A class that is not abstract and uses implements must write every abstract method of that interface itself, or inherit it from a superclass, and it is a compile-time error if even one is missing. When you use implements, the interface becomes a supertype of the class, so a variable of type List can point to an ArrayList object. If a class has methods with the same names but does not use implements, it does not become that interface type.
- Abstract method
- Why it exists — If you put an empty body { } in a method on the parent side, a class that inherits it compiles even if it does not write that method, and a method that does nothing is left behind. An abstract method has no body, so if the class forgets to write it, a compile-time error tells you.
- Where it's used today — compareTo of Comparable, run of Runnable, and compare of Comparator are abstract methods, so a class that follows these interfaces writes those methods itself. The body written as a lambda is also the body of one such abstract method.
- An abstract method is a method that declares only the name, the parameters, and the return type, and has no implementation (no body). In an interface, if you write only a semicolon where the body would go, as in int compareTo(T o); of Java's Comparable, it is an abstract method and is public even without writing abstract. If the body is a block of braces and not a semicolon, the method is an implementation even if the block is empty ({ }). A class that implements the interface that has an abstract method must write it, and it is a compile-time error if a class that is not abstract does not write it.
- extends
- Where it's used today — When you make your own exception class, write an exception class that Java provides after the new class name, as in extends RuntimeException, to inherit from it, and when you make a servlet, write extends HttpServlet. When a class follows an interface, use implements, not extends.
- extends is the keyword in a class declaration that says which class the class inherits from. You write it after the class name, as in class MemberNotFoundException extends RuntimeException. The class written after it (RuntimeException, which Java provides) is the superclass, and the class being declared (MemberNotFoundException, a name chosen for this example) is the subclass. A class can write only one class after extends, and a class marked final, such as String, cannot be inherited from with extends. When you use extends, the superclass becomes a supertype of the subclass, so a variable of the superclass type can point to an object of the subclass. A class that does not use extends has Object as its superclass.
- Type
- Why it exists — If the kind of a value is not decided, mistakes such as multiplying text or calling a method that does not exist show up only when the program is run and reaches that line. Java's types find such mistakes before running, at compile time.
- Where it's used today — You write it when declaring variables, parameters, and the values a method returns. An editor such as IntelliJ looks at the type and shows the list of methods that can be called on that value.
- A type is a name that decides what kind of value a variable can point to or hold. The types of Java are divided into primitive types and reference types, and the reference types are class types, interface types, type variables, and array types. A name can be used as a type only when there is a class or interface declaration for it. List (an interface) and ArrayList (a class) that Java provides are types declared in that way. On every line that puts a value in a variable, the compiler checks that the type of the value is the same as the type of the variable or a subtype of it, and it also looks up the methods you can call through the variable in the type of the variable. So through a variable of type List you cannot call trimToSize, which only ArrayList has, even if the actual object is an ArrayList.
Try these
- Default settings — The variable names, of the type List (an interface that Java provides), points to an ArrayList object. add and size are methods that List fixes, so you can call them on names.
- Swap in LinkedList — LinkedList is also a class that implements List, so the only place you changed is the right side of new. The code after it compiles as it is and prints the same list.
- Create it with new List<>() — List is an interface, so you cannot create an object from it with new. There is a compile-time error.
- Call trimToSize() on a List variable — Even if the actual object is an ArrayList, the compiler looks only at the type of the variable, List. List has no trimToSize, so there is a compile-time error.
- Make an ArrayList variable point to a LinkedList — A variable of type ArrayList cannot point to a LinkedList object, so there is a compile-time error. If you write the variable with a class type, you are tied to that class.
- Implement Comparable — Member, an example class that we made, implements Java's Comparable and writes compareTo, so Collections.sort sorts by age.
- compareTo without implements — Even if a method with the same name exists, without implements Member is not of type Comparable. There is a compile-time error on the Collections.sort line.
- implements without compareTo — An interface does not pass down the body of a method. You did not write compareTo yourself, so there is a compile-time error.
- Declare an interface yourself — interface Greeter, a name chosen for this example, fixes only the name of greet, and Hello implements it and writes the body. If you inherit a class with extends, you inherit the body too, but you can inherit only one class.
Running with the default settings
- The compiler finds the List that Java provides from the import line. List is declared in the Java standard library as public interface List<E>. It is declared with interface, not class, and it fixes that these methods exist: add (append to the end of the list), get (take out the element at a position), and size (the number of elements). <String> means the elements of this list are strings.
- The compiler checks new ArrayList<>() on the right of =. ArrayList is a class that Java declares as public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable. The bodies of add and size (the work they actually do) are written in it, so you can create an object with new. In the declaration, only one class (AbstractList) is written after extends, and four interfaces are written after implements. A class can inherit from only one class, but it can implement several interfaces.
- The compiler checks the line List<String> names = new ArrayList<>();. ArrayList implements List, so it is fine for the List variable names to point to a ArrayList object. The type of the variable is written as the interface List, and the object that is actually created is written as the class ArrayList.
- The compiler checks names.add(...) and names.size(). The compiler decides which methods you may call by looking only at the type of the variable, List. add and size are methods that List fixes, so you can use the same lines as they are whether the actual object is an ArrayList or a LinkedList.
- Compilation succeeds and the Main class file is made.
- java Main runs it. new ArrayList<>() creates a ArrayList object, and names points to that object. When you call names.add, the add that is written in ArrayList actually runs, and the three names are added to the list one after another. The first line prints [Alice, Bob, Carol], 3 names, and on the second line getClass().getSimpleName() prints ArrayList. getClass() is a method that every object has, and it tells you the class of the object that was actually created.
Result of this run
- An interface is a type that you declare with interface, and it fixes that certain methods exist. List, which Java provides, is an interface, and ArrayList is a class that implements it with implements List. That is why the List variable names could point to an ArrayList object.
- add and size, which were called on names, are methods that List fixes, so this code does not depend on whether names points to an ArrayList or a LinkedList. What ran was the add and size written in ArrayList.
Code
// Bring in what Java provides (java.util package)
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// List is an interface that Java provides; ArrayList and LinkedList are classes that Java provides
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Carol");
System.out.println(names + ", " + names.size() + " names");
System.out.println("names points to: " + names.getClass().getSimpleName());
}
}
Assumptions of this model
The compiler and runtime are JDK 21.0.12.1 (javac 21). For all of the combinations of the settings (12 for the list, 3 for sorting, and 2 for declaring an interface yourself), the text that the code function of the screen makes was written to a file exactly as it is and compiled with javax.tools, and the ones that compiled successfully were loaded with a new class loader, Main.main was run, and the results were checked against the standard output that was captured. What was checked is whether compilation succeeded, the diagnostic code and the English message of the first error (abstract.cant.be.instantiated, cant.resolve.location.args, prob.found.req, cant.apply.symbols, and does.not.override.abstract were turned into the five error descriptions on the screen), the number of errors and the lines where they occurred, whether the Main class file was made, and the output when run. In the same program, reflection was used to check that List and Comparable are interfaces, that ArrayList inherits from AbstractList and implements List, RandomAccess, Cloneable, and Serializable, that LinkedList inherits from AbstractSequentialList and implements List, Deque, Cloneable, and Serializable, that String implements Comparable, that trimToSize is in ArrayList but not in List, and that the methods of Comparable are only compareTo. It was also compiled separately that writing two classes after extends is a syntax error (javac says that { is expected where the comma is), and that writing two interfaces after implements compiles. The declarations shown on the screen (public interface List<E>, and <T extends Comparable<? super T>> of Collections.sort) were checked against the JDK 21 API documentation. The documentation followed the Java Language Specification (Java SE 21): Section 9.4 (an interface method that ends with a semicolon and has no body is an abstract method), Section 8.1.4 (one class after extends), Section 8.1.5 (several interfaces after implements), Section 8.1.1.1 (a class that is not abstract must have all the abstract methods of the interfaces it implements), Section 15.9.1 (you cannot create an object from an interface with new), Section 5.2 (a variable of a supertype can point to an object of a subtype), and Section 15.12.1 (the methods you can call are looked up in the type of the variable). The kinds of errors, their number, and the line where each occurs are not fixed by the specification but were observed on this javac, and when there are several errors, only the first is written in the table. List also has default methods that have bodies (sort, replaceAll, and so on), but this lab does not cover them. How interfaces are used, and how they differ from abstract classes, are covered in "In-depth lab: Interfaces and abstract classes".
Previous lab: Inheritance · Next lab: Exceptions