Comparator is a interface in java then how is it that it allows new Comparator() and overrides compare method? Are there any other classes/interfaces also like that? Please help its very confusing
Asked
Active
Viewed 56 times
1 Answers
1
You cannot do Comparator x = new Comparator();
What you can do is
Comparator x = new Comparator(){
// some implementation code here
};
That is something else (it includes the definition of an anonymous subclass of Comparator). It is more or less just a shorthand for declaring a new class that implements Comparator and making an instance of it and the same time.
And, yes, you can do that with all interfaces or non-final classes (don't need to be abstract).

Thilo
- 257,207
- 101
- 511
- 656