Reputation: 69
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:
Any input will be appreciated.
Upvotes: 3
Views: 90
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
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