minte9
LearnRemember



Default methods

Prior to Java 8, adding new methods to interfaces breaks existing implemenations.
 
/**
 * Starting with Java 8 ...
 * interfaces can have default method construct
 */

package com.minte9.effective.interfaces_default;

public class DefaultMethods {
    public static void main(String[] args) {

        new Login().subscribe();
            // Default subscribe method

        new Subscribe().subscribe();
            // Default subscribe method - overwritten
    }
}

interface Commandable {
    public abstract void getCommand();

    public default void subscribe() {  // Look Here 
        System.out.println("Default subscribe method");
    }
}

class Subscribe implements Commandable {
    @Override public void getCommand() {
    }

    @Override public void subscribe() {
        System.out.println("Default subscribe method - overwritten");
    }
}

/**
 * Old class - don't need to imnplement subscribe()
 */
class Login implements Commandable { 
    @Override public void getCommand() {
    }

    //subscribe() overwitten - not needed!
}

Contract

An interface is a contract, don't use interfaces for inheritance!
 
/**
 * Default methods for existing interfaces ...
 * should be avoided unless the need is critical. 
 * 
 * A default method added to an interface break main scope ...
 * which is to unsure a valid contract betwween classes.
 */

package com.minte9.effective.interfaces_default;

public class Contract {
    public static void main(String[] args) {

        new Subscribe();
    }
}

interface A {
    public default void getCommand() {
    }
    public default void subscribe() {        
    }
}

class B implements A {
    
    // there is no need to override subscribe() so ... 
    // the contract is no longer valid!
}



  Last update: 213 days ago