There's two things you might be talking about:
public static void sort(List list, Comparator c){ ... }
Here, the parameter list
has the interface type List
but anyone who calls the method will have to pass in an instance of a concrete class like ArrayList
that implements the interface, and the code of the method will call the methods of that concrete class - this mechanism is called "dynamic method dispatch" and lies at the heart of the core OO principle of polymorphism.
sort(myList, new Comparator(){
public int compare(Object o1, Object o2){
...
}
});
This is an example of an anonymous class: the code actually defines a new class without a name that implements the Comparator
interface, and at the same time creates an instance of that class. This is used in Java mainly for things where other languages would use language constructs such as function pointers, closures or callbacks: to pass a piece of code to be executed within the method you're calling.