官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 石泉县| 调兵山市| 岗巴县| 中江县| 鄯善县| 家居| 泰和县| 济源市| 三门峡市| 鹤峰县| 原平市| 堆龙德庆县| 肇东市| 友谊县| 探索| 马鞍山市| 潞西市| 五大连池市| 徐州市| 互助| 梨树县| 铜梁县| 道孚县| 航空| 宁都县| 潜江市| 托克逊县| 哈尔滨市| 桦甸市| 北辰区| 祁连县| 白朗县| 宜都市| 南京市| 体育| 福鼎市| 佛坪县| 扎鲁特旗| 土默特右旗| 靖宇县| 青海省|