- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 277字
- 2021-07-02 19:01:56
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.
- Learning Single:page Web Application Development
- Advanced Quantitative Finance with C++
- Apache Oozie Essentials
- 計算機圖形學編程(使用OpenGL和C++)(第2版)
- 簡單高效LATEX
- C語言程序設計基礎與實驗指導
- PhoneGap Mobile Application Development Cookbook
- 圖數據庫實戰
- 大話Java:程序設計從入門到精通
- GameMaker Essentials
- Angular應用程序開發指南
- Practical GIS
- 深度學習程序設計實戰
- Akka入門與實踐
- Shopify Application Development