Implementation before Java 7

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

Implementation in Java 7

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

Implementation since Java 8

Implement interface through a lambda expression

    
File dir = new File("/home/arturo");
File[] javaFiles = dir.listFiles(file -> file.getName().endsWith(".java"));
    

Implementation before Java 7

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

Implementation in Java 7

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

Implementation since Java 8

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