nemesis
nemesis

Reputation: 263

creating an object and defining method at the same time

Is it possible to declare a method while creating an object? I ran across the following lines of code in java:

public static void main(String[] args) {
        Comparator<String> comparator = new Comparator<String>() {
            public int compare (String s1, String s2) {
                return s1.compareToIgnoreCase(s2);
            }
        };
}

And it looks like that while creating the object comparator, the code is adding a method to implement the Comparator<T> interface. Is adding additional methods always possible when creating instances, or is it something in particular that's related to a java interface?

Thanks for any help!

Upvotes: 0

Views: 284

Answers (2)

Priyank Doshi
Priyank Doshi

Reputation: 13151

This is not what you think it is.

Whatever follows new Comparator<String>() is a anonymous inner class. It means that the anonymous class is implementor of Comparator class.

You can have two oprions :

1. AnyClass object = new AnyClass() { // anonymous inner class starts here.
// In this case , inner class is a sub class of AnyClass.
};// ends here
2. AnyInterface anyInterface = new AnyInterface() { //anonymous inner class starts here.
// In this case , inner class is implementer of AnyInterface.
}; // ends here.

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Yes, you can do that. It's called Anonymous Class. It means that you're creating a new class inside the method but you're not giving it a name (that's why it's anonymous). In your example, this anonymous class implements the Comparator<String> interface, and it should define the compare method in its body. That's why the code works.

Upvotes: 1

Related Questions