Q: What is an interface?
A: An interface is a set of requirements for a class. However, unlike abstract classes, a class can conform to one or many interfaces.
Q: Are interfaces classes?
A: No, they are not classes. The best way to think of a class is as a person, place or thing. An interface is none of those, instead, think of them as a service provider
Say that you want to be able to sort all classes that implement the compareTo interface. First, you would need to define the interface compareTo.
public interface Comparable {int compareTo(Object other); //automatically public}
Then, in your following class that implements the interface Comparable, you would modify the class header and override the compareTo service that the interface provided
public class Employee implements Comparable{public int compareTo(Object otherObject){Employee other = (Employee) otherObject;return Double.compare(salary, other.salary);}. . .}
In this case, we made employees compareTo themselves reguarding the salary.
Python data model note: Think of this as operator overloading, all classes can respond to certain “operators” to make the classes more user friendly. Also notice that this implementation uses Double (wrapper class)’s compareTo method
Note: you can do away with casting and use generics, this way the syntax is way friendlier and readable
class Employee implements Comparable<Employee>{public int compareTo(Employee other){return Double.compare(salary, other.salary);}. . .}
Python data model note: just like how itemOf can lead to implementations with random.shuffle() and itertools.enumerate(), so too can comparibles lead to implementations of sorting algorithims
if (a[i].compareTo(a[j]) > 0){// rearrange a[i] and a[j]. . .}
Here, the interface compareTo’s implemetnation in object a[i]’s class is used in a sorting algorithim.
Q: how does the compiler know that a[i].compareTo(a[j])is valid?
A: The compiler does not know, you declare the method itself to act on comparable objects in the following line:
public static void sort(Comparable[] a)
Q: Can you instantiate an interface?