PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   03-10-2021

DEFAULT METHODS

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

class App {

    public static void main(String[] args) {

        new Login();
        new Subscribe();
    }
}

interface Commandable {
    public abstract void getCommand();
    public default void subscribe() {} // Look Here
}

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

/**
 * Old class - don't need to imnplement subscribe()
 */
class Login implements Commandable { 
    @Override public void getCommand() {}
}
... 18 lines
 
p104 Default methods for existing interfaces should be avoided unless the need is critical.
 
/**
 * An interface is a contract.
 * Don't use interfaces for inheritance!
 */
class App {

    public static void main(String[] args) {

        new Subscribe();
    }
}

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

class Subscribe implements Commandable {
    
    // there is no need to override subscribe() so ... 
    // the contract is no longer valid!
}
... 11 lines
 

Questions    
Import Static

        A B C D E F
🔔
1/1