I have seen we can pass any types of arguments in 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");
}
}
Here in listFiles method we are passing Interface thing. It seems that Interface object is being created, but as far I know it cannot be done. It just refer the object of class which implements that interface.
Being said that "It's just a way of saying "this parameter will accept any object that supports this interface. It's equivalent to accepting some object of a base class type, even if you're passing in a subclass." NOT CLEARED
Questions:
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()** ?
Can anyone help me to understand this ? I'm really confused here
2 Answers 2
To answer your questions, let's take one by one
1) new FileFilter() of which class object is being created here ?
It will be an object of anonymous class. See Can we create an object of an interface?
2) If we are using interface in class, then why its not implemented in above class ?
It does not require to implement from main class. You are just referring a interface in your class which does not have to be implemented.
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() ?
Yes in that case, all method needs to be implemented.
7 Comments
new ImplementedInterface(){all methods}.Anonymous classes can implement interfaces, and that too without the "implements" keyword.
More stackoverflow links: Can we create an instance of an interface in Java? , Can we create an object of an interface?
On a side note, You have hit a case of Functional Interface which have been introduced in Java 8. An interface with exactly one abstract method is called Functional Interface.
Read more about functional interfaces here: https://www.journaldev.com/2763/java-8-functional-interfaces
FileFilterinterface.