简体   繁体   中英

Can I have a Interface in method?

I know that that on can have a class declaration in a method of class. Eg. We can have anonymous class declaration for event handling in a method body.

But I want to know that same way can I have Interface declaration in a method in a class.

What is use of that?

I' assuming you are refering to returning an interface for a method?

Short answer: Yes.

Why?

Here's a good post.
Why we return type Mostly Interface rather than Class?

Excerpt:

The benefit is that returning an interface makes it possible to change the implementation later on. Eg, you might decide after a while that you'd much rather use a LinkedList instead of an ArrayList.....

I don't think you can declare an Interface inside a method. Why would you want to? You can only define an anonymous inner class.

No. why don't you just write one, compile, and see for yourself?

Suppose an interface can be declared inside a method, it wouldn't be accessible outside. It's hard to imagine the usefulness of such an interface confined in a block. A local class on the other hand can be useful since it contains concrete implementation.

You can do that, a well known example is the Comparator<T> interface.

For example:

List<Person> persons = personDAO.list();

Collections.sort(persons, new Comparator<Person>() { 
    // Anonymous inner class which implements Comparator interface.
    public int compare(Person one, Person other) {
        return one.getName().compareTo(other.getName());
    }
});

Some may argue against this and tell that it rather belongs in the Person class, so that you don't need to implement it again and again whenever needed. Eg

public class Person {

    // ...

    public static final Comparator<Person> ORDER_BY_NAME = new Comparator<Person>() {
        public int compare(Person one, Person other) {
            return one.getName().compareTo(other.getName());
        }
    };
}

which can be used as follows:

Collections.sort(persons, Person.ORDER_BY_NAME);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM