Define a class that implements interface and instantiate it
public class JavaFileFilter implements FileFilter
{
@Override
public boolean accept(File file)
{
return file.getName().endsWith(".java");
}
}
// Main
File dir = new File("/home/arturo");
File[] javaFiles = dir.listFiles(new JavaFileFilter());
Define an anonymous class when we need this object
File dir = new File("/home/arturo");
File[] javaFiles = dir.listFiles(new FileFilter()
{
@Override
public boolean accept(File file)
{
return file.getName().endsWith(".java");
}
});
Implement interface through a lambda expression
File dir = new File("/home/arturo");
File[] javaFiles = dir.listFiles(file -> file.getName().endsWith(".java"));
Define a class that implements interface and instantiate it
public class MyRunnable implements Runnable
{
@Override
public void run()
{
for(int i = 0; i < 3; i++)
{
System.out.println("This is thread: " +
Thread.currentThread().getName());
}
}
}
// MAIN
Runnable run = new MyRunnable()
Thread t = new Thread(run);
t.start();
Define an anonymous class when we need this object
Runnable run = new Runnable()
{
@Override
public void run()
{
for(int i = 0; i < 3; i++)
{
System.out.println("This is thread: " +
Thread.currentThread().getName());
}
}
};
Thread t = new Thread(run);
t.start();
Implement interface through a lambda expression
Thread t = new Thread(() -> {
for(int i = 0; i < 3; i++)
{
System.out.println("This is thread: " +
Thread.currentThread().getName());
}
});
t.start();