Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a program to demonstrate default methods in Interfaces in Java 8.
- Default methods are introduced in Java 8 to provide a default implementation for methods in an Interface.
- Using this feature, new functionality can be added to the existing interfaces without breaking the code.
- “default” keyword is specified while providing the implementation for a method in an Interface.
Let’s look at an example program:
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
package com.clearurdoubt; /** * * @author Sai Gowtham Badvity * Default Method Implementation demo in Java 8 * */ interface IA { // Normal abstract method void someIAMethod(); // Default method implementation in IA default void doSomething() { System.out.println("This is a default implementation of doSomething() in IA."); } } interface IB extends IA { // Normal abstract method void someIBMethod(); // Default method implementation in IB default void doSomething() { //IA.super.doSomething(); // This statement plays an important role System.out.println("This is a default implementation of doSomething() in IB."); } } class AB implements IA, IB // AB implements both the interfaces { @Override public void someIAMethod() // IA specific method implementation { System.out.println("someIAMethod() method implementaion."); } @Override public void someIBMethod() // IB specific method implementation { System.out.println("someIBMethod() method implementaion."); } } // Let's see the default method implementation feature public class DefaultMethodDemo { public static void main(String[] args) { IA referenceIA = new AB(); IB referenceIB = new AB(); // Output of below method calls are normal as per the expectation referenceIA.someIAMethod(); referenceIB.someIBMethod(); // The output of the below methods will be interesting. referenceIA.doSomething(); referenceIB.doSomething(); } } |
Output:
Instead of specialized behavior, if the child interface wants to use its parent default method implementation, below syntax is used:
<ParentInterfaceName>.super.<methodName>();
So if we comment the line 32 and uncomment line 31 in the above program, the output would be:
Happy Learning :).
Please leave a reply in case of any queries.