[英]passing Interface as parameter in Method
我已经看到我们可以在Method中传递任何类型的参数。
import java.io.File;
import java.io.FileFilter;
public class LastModified {
public static File lastFileModified(String dir) {
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
long lastMod = Long.MIN_VALUE;
System.out.println("lastMod:"+lastMod);
File choice = null;
for (File file : files) {
System.out.println("File:"+file);
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
return choice;
}
public static void main(String[] args) {
lastFileModified("D:\\TestFiles");
}
}
在listFiles方法中,我们正在传递Interface事物。 似乎正在创建Interface对象,但据我所知它无法完成。 它只是引用实现该接口的类的对象。
有人说“这只是一种说法”,此参数将接受支持此接口的任何对象。 这等效于接受基类类型的某些对象,即使您要传递子类也是如此。” NOT CLEARED
问题:
1) **new FileFilter()** of which class object is being created here ?
2) If we are using interface in class, then why its not implemented in above class ?
3) If its a one more way to implement, then what if that interface would have 10 declared methods ? So Do we need to define all after **new FileFilter()** ?
谁能帮助我了解这一点? 我真的很困惑
为了回答您的问题,让我们一一讲解
1)在这里创建哪个类对象的new FileFilter()
?
它将是匿名类的对象。 请参阅我们可以创建接口的对象吗?
2)如果我们在类中使用接口,那么为什么不在上述类中实现呢?
它不需要从主类执行。 您只是在类中引用了不必实现的接口。
3)如果是一种实现的方法,那么该接口将有10个声明的方法怎么办? 那么,是否需要在new FileFilter()
之后定义所有内容?
是的,在这种情况下,需要实施所有方法。
匿名类可以实现接口,而且也可以不用“ implements”关键字。
更多stackoverflow链接: 我们可以在Java中创建接口的实例吗? , 我们可以创建接口的对象吗?
附带说明一下,您碰到了Java 8中引入的Functional Interface的情况。具有一种抽象方法的接口称为Functional Interface。
在此处阅读有关功能接口的更多信息: https : //www.journaldev.com/2763/java-8-functional-interfaces
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.