Java 8 default methods

Why

OK, so interfaces can now provide a default implementation. This makes sense if you want to be able to add new methods to your interface without breaking existing implementations. Oracle uses default methods quiet extensively (see java.util.Collection).

Simple example

public class SimpleExample {
    
    interface Interface1 {
        
        default void test() {
            System.out.println("-- default test");
        }     
        
        default void test2() {
            System.out.println("-- default test2");
        }
    }
    
    static class Implementation1 implements Interface1 {
        
        public void test2() {
            System.out.println("my own implementation");
        }                      
    }
    
    public static void main(String[] args) {
        Interface1 if1 = new Implementation1();
        
        if1.test();
        if1.test2();
    }   
}

Guess what the program will output.

-- default test
my own implementation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.