Steel Man
Steel Man

Reputation: 69

Java interface/ Comparator

I am new to java and trying to understand some concepts. Here is a piece of code I don't understand.

public static Comparator<Fruit> FruitNameComparator = new Comparator<Fruit>() 
{
    public int compare(Fruit fruit1, Fruit fruit2) 
    {
        return fruit1.quantity - fruit2.quantity;
    }
};

I know what this is doing, but can't understand why this is allowed. So my questions are:

  1. From the java doc, Comparator[T] is an interface. How about Comparator[Fruit]? I will suppose that it is a class, because it has to override the compare function.
  2. Why can FruitNameComparator be intialized with a non-parameter constuctor and a class definition within the {}? I didn't find such constructor declaration in javadoc of Comparator[T].

Any input will be appreciated.

Upvotes: 3

Views: 90

Answers (2)

Bohemian
Bohemian

Reputation: 425053

It's an anonymous class, which is an in-line concrete implementation of a type (either a super class or an interface).

Implementations are provided for whatever abstract methods are declared by the type.

In the case of super classes, the constructor called can not be specified, so arguments must be provided if there's not a default/no- args constructor.

In the case of interfaces, no parameters may be specified in the constructor because interfaces can not declare constructors.


Btw, I would be inclined to name your field fruitQuantityComparstor, rather than fruitNameComparator, as it compares quantities, not names.

Upvotes: 0

rgettman
rgettman

Reputation: 178263

This code is using a feature of Java called anonymous inner classes. You specify the interface or superclass to implement/extend, along with an anonymous class body. Your anonymous inner class implements Comparator<Fruit>.

Upvotes: 5

Related Questions