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

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.

主站蜘蛛池模板: 云霄县| 那坡县| 定结县| 翁牛特旗| 漳平市| 夏津县| 兰溪市| 深州市| 文昌市| 鄂托克旗| 克什克腾旗| 乌鲁木齐市| 苗栗市| 宾阳县| 成安县| 奉新县| 海晏县| 临海市| 铜鼓县| 日土县| 凌源市| 高唐县| 揭阳市| 临沧市| 肃北| 佛学| 五寨县| 日土县| 枣强县| 东明县| 门源| 阳山县| 漳州市| 沾化县| 刚察县| 北宁市| 巨野县| 黄大仙区| 镇巴县| 辽宁省| 历史|