Monday, 22 December 2014

STATIC METHODS & DEFAULT METHODS IN AN INTERFACE - JAVA 8 EXICITING FEATURES

Static Methods in interfaces

Prior to Java 8, we have many utility classes with static methods which are commonly used.

For Example, for Collection interface, we have utility class Collections


likewise,

path - Paths

Executor - Executors

So, To reduce the utility classes, java designers introduced static methods
in interfaces.

Note:

. A static method contains a static modifier.

. They are implicitly public.

. Have implementation logic within the interface.

 
Example:

public interface Blog {

    int  followers_count  = 0;

    void comment();

    //A static convenience method

   public static  void subscribe(){

          //implementation logic

        System.out.println("you have successfully subscribed");

   }

}


DEFAULT METHODS in an interface 

From Java 8,  you can also declare DEFAULT methods in interface.


DEFAULT METHODS is new feature added in Java 8.


To understand the concept of default methods and its purpose, lets consider that
I have designed a library which is having the above declared interface Blog.

Lets take an assumption that, those who want to make blog must implement my interface Blog.

So I have distributed the interface to all the interested people who want to blog.

 Now, the many of my bloggers are satisfied with the methods available in the 
interface.

But, If one of the bloggers wants to add his/her own methods to the interface, like say adding a new method share().

So They would have to request me to add the method share() method and again I would distribute the library to all the bloggers.

Now, If the bloggers try to use the this new library - the old code breaks because 
share() method must be implemented by all the bloggers.

In java 8, this problem is alleviated by introducing DEFAULT methods in the interface.

default methods have a default modifier and an implementation logic in the interface itself.

So, If I make share() as a default method in the interface - old code breaking problem will be solved.

Thanks to Default methods.

Note:

. Must have a default modifier

. have an implementation logic within the interface.


Example:


public interface Blog {

    int  followers_count  = 0;

    void comment();

    //A static convenience method

   public static  void subscribe(){
        
          System.out.println("you have successfully subscribed");

   }

  default String share(){
         
             System.out.println("You have shared your blog"); 

             return "Success";

  }

}



 Hope this is helpful.                                                     
   
 If you like this, please share.

No comments:

Post a Comment