Java 8 Default Methods For Interfaces!

What is the Default Methods for Interfaces?

Java 8 enables adding non-abstract methods to interfaces using static or default keywords.

  • Static Keyword: you can add a non-abstract static method to an interface and call it using interface name. – Can’t be overridden.
  • Default Keyword: you can add a non-abstract method to an interface and override it in the interface implementation, but if you didn’t override it you will have the default implementation in the interface.
public class DefaultMethods {
    interface Calculator {
        void add();

        // Can't be overridden.
        static void subtract() {
            System.out.println("Calculator Subtract Method");
        }

        default void multiply() {
            System.out.println("Calculator Multiply Method");
        }
    }

    class FirstCalculator implements Calculator {

        @Override
        public void add() {
            System.out.println("FirstCalculator Add Method");
        }

        public void multiply() {
            System.out.println("FirstCalculator Multiply Method");
        }
    }

    class SecondCalculator implements Calculator {
        @Override
        public void add() {
            System.out.println("SecondCalculator Add Method");
        }
    }

    public static void main(String[] args) {
        DefaultMethods defaultMethods = new DefaultMethods();

        Calculator firstCalculator = defaultMethods.new FirstCalculator();
        Calculator secondCalculator = defaultMethods.new SecondCalculator();

        Calculator.subtract(); // Calculator Subtract Method

        firstCalculator.add(); // FirstCalculator Add Method
        secondCalculator.add(); // SecondCalculator Add Method

        firstCalculator.multiply(); // FirstCalculator Multiply Method
        secondCalculator.multiply(); // Calculator Multiply Method
    }
}