Implementing a JDK interface: Comparable
Collections.sort was written years before Student existed. The Comparable contract is what connects them. More in Topic 9.10.
An interface is a named list of abilities, a contract, that any class can promise to provide with implements. A class can implement many interfaces, and code written against an interface works with every class that implements it.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Create an interface Shape with double area() and implement it in Circle and Square. Compute the largest area in a List<Shape>.
Create interfaces Readable (String read()) and Writable (void write(String s)) and a ReadWrite interface extending both. Implement it with a class that stores the last written string.
Make Product(String name, double price) implement Comparable<Product> by price ascending and sort a list.
Explain it without notes
What is an interface, and what does a class promise when it implements one?
Why can a class implement many interfaces but extend only one class?
What does 'program to an interface' mean, and why is it useful?
What are the implicit modifiers of methods and fields in an interface?
Expected output
[Ravi(95), Zoya(88), Asha(82)]