6

I know that an interface cannot have constructors and we cannot make object of interface.

This is not possible:

Comparator cmp = new Comparator(); 

I don't understand how is it possible to make an anonymous inner class with the keyword "new Comparator()". Doesn't this keyword create an object of the type Comparator?

Here is the complete code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class DemoApp {

    public static void main(String args[]) {

        List<String> animals = new ArrayList<>();
        animals.add("elephant");
        animals.add("snake");
        animals.add("lion");
        animals.add("mangoose");
        animals.add("cat");
        animals.add("tiger");

        Collections.sort(animals, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return -s1.compareTo(s2);
            }
        });
        displayList(animals);
    }

    public static void displayList(List<String> anim) {
        for (String animal : anim) {
            System.out.print(animal + " "); 
        }
        System.out.println();
    }
 }
Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
elvis
  • 956
  • 9
  • 33
  • 56
  • 2
    You already know it is using an anonymous class. So you are creating an instance of that class that implements the interface. What are you uncertain about? – khelwood Apr 20 '18 at 08:46
  • Implicitly you are creating an implementation of the _Comparator_ interface, and implementing its _compare_ method – mkuligowski Apr 20 '18 at 08:46
  • 2
    When you create an anonymous class like `new Comparator() {...}` you actually create a class instance that implements a `Comparator` interface. – Oleksandr Pyrohov Apr 20 '18 at 08:47
  • 1
    Possible duplicate of [How are Anonymous (inner) classes used in Java?](https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java) – daniu Apr 20 '18 at 08:47

4 Answers4

10

Doesn't this keyword create an object of the type Comparator?

Yes it does, but it doesn't create an instance of class Comparator (since Comparator is not a class).

It create an instance of an anonymous class that implements the Comparator interface. Since that class instance implements Comparator, you can say that its type is Comparator.

Eran
  • 387,369
  • 54
  • 702
  • 768
4

When you are writing such an expression:

Collections.sort(animals, new Comparator<String>() {
    public int compare(String s1, String s2) {
        return -s1.compareTo(s2);
    }
});

What you are really doing is:

class ClassNameHere implements Comparator<String> {
    public int compare(String s1, String s2) {
        return -s1.compareTo(s2);
    }
}
Collections.sort(animals, new ClassNameHere());

This code doesn't work:

Comparator comp = new Comparator();

Because, as you know, you can't instantiate an interface. In both previous pieces of code, you are not instantiating an interface, you are instantiating a class instead, and that's ok.

You are confused because the code you wrote is a shorthand for the one I wrote, but it's in fact the same thing.

Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
RaffoSorr
  • 405
  • 1
  • 5
  • 14
-2

you can create Compartor like so (like you did)

Comparator cmp = new Comparator<String>() {
  public int compare(String s1, String s2) {
    return -s1.compareTo(s2);
  }
};

you just have to implement it's function compare cause it's an abstract class

in this case you do have an instance of Compartor

System.out.println(cmp.getClass().getName()); //anonymous class
System.out.println(Comparator.class.isInstance(cmp));

output

MyClass$1
true
shahaf
  • 4,750
  • 2
  • 29
  • 32
  • the OP's question is why this code doesn't work `Comparator cmp = new Comparator(); ` – shahaf Apr 20 '18 at 08:50
  • Yes, the question is why, not how to use it – Stefan Apr 20 '18 at 08:51
  • You just copy/pasted part of OP's code. OP clearly knows that their code "works" but wants to know _why_, given their belief that one can't create a `new Comparator()`. You haven't explained _why_ or _how_ instantiating an anonymous inner class is different. – k_ssb Apr 20 '18 at 08:52
  • I think you better let the person who asks the question decides... thanks for the down votes though... – shahaf Apr 20 '18 at 08:57
  • No, the question is why this works (see the code of the OP) `new Comparator() { public int compare(String s1, String s2) { return -s1.compareTo(s2);. } }` -Your "answer" just copied parts of the OP's question. – Erwin Bolwidt Apr 20 '18 at 08:57
  • guys I don't think you read my answer till the end.. just saw the first code block, shame... cause the other answers aren't true... – shahaf Apr 20 '18 at 09:04
  • Your answer has improved with these edits, but Eran's answer was already sufficient and to the point. What the class name of the anonymous class is, doesn't matter all that much. – Stefan Apr 20 '18 at 09:07
-2

Anonymous class is an inner class without a name and for which only a single object is created, so the object created here is an instance of an anoymous class that implements Comparator.

Oussama Werfelli
  • 513
  • 3
  • 14
  • 1
    This answer doesn't really add something not already stated in other answers – Stefan Apr 20 '18 at 08:52
  • Why do you think that only a single object is created of an anonymous inner class? That's not true - every time that the `new` expression is invoked, it creates another instance of the same anonymous class. – Erwin Bolwidt Apr 20 '18 at 08:54
  • According to that I sad that is a single object https://www.geeksforgeeks.org/anonymous-inner-class-java/. With anonymous classes you can use only one new, when you put another new you should create another implementation, so it's an another anonymous class – Oussama Werfelli Apr 20 '18 at 09:00