What is it?
- Private method in interface with implementation.
- Private method can be used within default or static methods within interface. Learn about Default Methods in interface
Example:
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 45 46 47 48 49 50 51 52 53 |
package ravi.tutorial.java.java9; /* * Demo of private method in interface */ public class PrivateInterfaceTest { public static void main(String[] args) { new Dog().makeAnimalNoise(); new AncientUnkownAnimal().makeAnimalNoise(); } } /* * Interface with default method. */ interface Animal { // Method with default implementation public default void makeAnimalNoise() { /* * Use private interface method here !!!!! */ System.out.println(getDefaultAnimalNoise()); } /* * PRIVATE INTERFACE METHOD. */ private String getDefaultAnimalNoise() { return "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 ! |