开发者

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 开发者_如何学Pythonknow 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. E.g., 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. E.g.

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜