我发现我们可以在方法中传递任何类型的参数。
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 对象,但据我所知,这是无法完成的。它只是引用实现该接口(interface)的类的对象。
有人说“这只是一种说法”,该参数将接受任何支持该接口(interface)的对象。它相当于接受基类类型的某个对象,即使您传递的是子类。”未清除
问题:
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()
这里正在创建哪个类对象?
它将是一个匿名类的对象。请参阅Can we create an object of an interface?
2)如果我们在类中使用接口(interface),那么为什么它不在上面的类中实现?
它不需要从主类实现。您只是在类中引用一个不必实现的接口(interface)。
3) 如果它是另一种实现方式,那么如果该接口(interface)有 10 个声明的方法怎么办?那么我们需要在 new FileFilter()
之后定义所有内容吗?
是的,在这种情况下,所有方法都需要实现。
关于java - 将接口(interface)作为方法中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48395292/