CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development Adriana Picoral
Interface
An interface class is a class that is 100% abstract (no concrete members).
There’s special keyword for it: interface
Like abstract methods in an abstract class, interface method signatures form a contract with the classes that implement that interface (another keyword: implements)
Interface
Non-instantiable (cannot use new)
Contain method signatures (and nothing else)
Use implements keyword to implement
A class may implement multiple interfaces
Each interface signature must be implemented
Interfaces specify what, not how
Interface
When a class implements an interface, it has an “is-a” relationship with the interface
Why Have Interfaces?
Code development and abstraction: Define “what” before the “how” is implemented
Faster design
Program maintenance: Easier maintenance and resilience to change
Flexibility
ensure compatibility across changes
Comparable Interface
“This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.”
Here’s what the Comparable interface looks like:
public interface Comparable<T> { int compareTo(T obj);}
Example of compareTo use
import java.util.Arrays;public class Example { public static void main(String[] args) { String a = "A"; String b = "B"; System.out.println(a.compareTo(b)); }}