What is it?
- Method in interface with default keyword.
- Method marked default will have an implementation within interface itself.
- Subclasses can override & provide custom implementation. If subclass does not provide, then default implementation from interface will be used.
When is it needed?
- If interface was introduced long back & has many sub classes. Now you want to add new method but don’t want to impact existing sub classes.
- If you don’t want to enforce all subclasses to implement method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package ravi.tutorial.java.java8; /* * Demo of default method in interface */ public class DefaultMethodDemo { public static void main(String[] args) { new Dog().makeAnimalNoise(); new AncientUnkownAnimal().makeAnimalNoise(); } } /* * Interface with default method. */ interface Animal { // Method with default implementation so that subclass is not enforced to // implement. public default void makeAnimalNoise() { System.out.println("Default Animal Noise !"); } } /* * Implementer of Animal with overridden method. */ class Dog implements Animal { // Implement method with proper logic @Override public void makeAnimalNoise() { System.out.println("Bark !"); } } /* * Implementer of Animal without overridden method. */ class AncientUnkownAnimal implements Animal { /* * Not implemented since noise not known. Default implementation will work for * this. */ } |
Output:
1 2 |
Bark ! Default Animal Noise ! |