Default method in interface

The default method is another extension in an interface provided in Java 8. An interface can consist of default methods. Classes that implement that interface may or may not implement the default method. Default methods are useful to extend an existing interface. Suppose you have an interface that is implemented by a lot of classes. Now, you want to extend functionality of the interface.

The first option you have is to add a new abstract method in the interface and force every class to implement it, which will break the existing implementation and require lots of new code. The second option is to add default methods in the interface, if some class wants to override them, it is free to do that. With this option, an existing implementation won't break as well. The foreach method in an iterable interface is the classic example of extending functionality using default methods.

Default methods can be created using default keywords. Let's change the static method in the preceding example to the default method:

public interface MyInterface { 
   default String hello() { 
      return "Inside static method in interface"; 
   } 
   void absmethod(); 
} 

The class implementing this interface does not need to provide the implementation of this method:

public class MyInterfaceImpl implements MyInterface { 
   @Override 
   public void absmethod() { 
      System.out.println("Abstract method implementaion in class"); 
   } 
}

Now, let's try to call the default method:

public class MyInterfaceDemo { 
  public static void main(String[] args) { 
     System.out.println(MyInterface.hello()); // won't compile 
     MyInterfaceImpl obj =new MyInterfaceImpl(); 
     obj.hello(); // works 
  } 
} 

Note that default methods are instance methods. They can be called using the instance of the class that implements the interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.8