繁体   English   中英

我可以在方法中使用接口吗?

[英]Can I have a Interface in method?

我知道在类的方法中可以有一个类声明。 例如。 我们可以在方法主体中使用匿名类声明进行事件处理。

但是我想知道我可以在类的方法中使用接口声明的相同方式。

这有什么用?

我假设您是指返回方法的接口?

简短的回答:是的。

为什么?

这是个好帖子。
为什么我们返回类型多数为接口而不是类?

摘抄:

好处是返回接口可以在以后更改实现。 例如,您可能会在一段时间后决定,您宁愿使用LinkedList而不是ArrayList .....

我认为您不能在方法内部声明接口。 你为什么要 您只能定义一个匿名内部类。

不,您为什么不只编写一个,编译并自己查看?

假设接口可以在方法内部声明,则无法在外部访问。 很难想象将这种接口限制在一个块中的有用性。 另一方面,局部类可能有用,因为它包含具体的实现。

您可以执行此操作,一个著名的示例是Comparator<T>接口。

例如:

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());
    }
});

有人可能对此表示反对,并说它属于Person类,因此您无需在需要时一次又一次地实现它。 例如

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());
        }
    };
}

可以如下使用:

Collections.sort(persons, Person.ORDER_BY_NAME);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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