Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Monday, September 22, 2014

Method definition inside an interface in java 1.8 : Default method in Java

Did you know from java 1.8 you can define a method inside an interface?


As per the explanation from Oracle

An example that involves manufacturers of computer-controlled cars who publish industry-standard interfaces that describe which methods can be invoked to operate their cars. What if those computer-controlled car manufacturers add new functionality, such as flight, to their cars? These manufacturers would need to specify new methods to enable other companies (such as electronic guidance instrument manufacturers) to adapt their software to flying cars. Where would these car manufacturers declare these new flight-related methods? If they add them to their original interfaces, then programmers who have implemented those interfaces would have to rewrite their implementations. If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

Few important points.

  • To make a method as default method it must be started with the keyword default
  • You need not to override default method in the implementation class.
  • Default methods are by default available in the implementation class and can be invoked using an object of that class.


A simple example
//interface DefaultMethod.java

interface DefaultMethod {
      
       //abstract Method
       public void methodA();
      
       //static methods
       static void methodB()
       {
              System.out.println("Inside Method B");
       }
      
       //default Method
       default void newDefaultMethod()
       {
              System.out.println("\n Default Method");
       }
}


//class DefaultMethodImplementation.java which implements DefaultMethod interface.

public class DefaultMethodImplementation implements DefaultMethod {
      
       public void methodA(){           
              System.out.println("\n Inside A");      
       }

       public static void main(String[] args) {       
              DefaultMethodImplementation dmi=new DefaultMethodImplementation();  
              dmi.methodA();
              dmi.newDefaultMethod();          
       }

}

Output of the above Java Program:



Happy Learning :) 
Post your questions in the comment box.

3 comments:

Anonymous said...

Nice example.

Akash Jain said...

Thanks ! Keep sharing.

Syed Shakir said...

What is the difference between new interfaces with default method implementations and Abstract classes