Java Language Basic usage of default methods

Download Java Language for free

Example

/**
 * Interface with default method
 */
public interface Printable {
    default void printString() {
        System.out.println( "default implementation" );
    }
}

/**
 * Class which falls back to default implementation of {@link #printString()}
 */
public class WithDefault
    implements Printable
{
}

/**
 * Custom implementation of {@link #printString()}
 */
public class OverrideDefault
    implements Printable {
    @Override
    public void printString() {
        System.out.println( "overridden implementation" );
    }
}

The following statements

    new WithDefault().printString();
    new OverrideDefault().printString();

Will produce this output:

default implementation
overridden implementation

Accessing other interface methods within default method