New Features of Java 8: Default interface methods and static interface methods, new features of Java 8

Source: Internet
Author: User

New Features of Java 8: Default interface methods and static interface methods, new features of Java 8
Interface Definition

The function of an interface is to define the functions required by an instance of this type, that is, the tasks that must be executed, and you do not need to care about how these tasks are implemented. The method defined by the interface does not have a method body, and the interface cannot define instance variables. If a class implements this interface, it must implement all methods of the rewrite interface. The interface is as follows:

1 public interface MyInterface{2     int getInt();3 }
Interface advantages

The interface is designed to support runtime dynamic method parsing. Generally, in order to call methods of another class from one class, both classes need to exist during compilation. Such requirements cause non-scalability of the class system. The interface is designed to enhance the class scalability. For details, refer:

    public interface MyInterface{        int getInt();    }
    public class MyInterfaceImpl implements MyInterface{        @Override        public int getInt(){            return 6;        }    }
Public classMain {public static void main (String [] args) {MyInterface my = null; // obtain the instance my. getInt ();} of MyInterfaceImpl or MyInterfaceImpl1 Based on the factory or other methods ();}}

In the above Code, during compilation, the compiler cannot determine the implementation class of the current "my" object. It can be determined only when the corresponding instance is created during running, so as to better implement the polymorphism feature.

Differences between classes and interfaces
  • The member variables can be defined in the class, but the member variables cannot exist in the interface.
  • No specific implementation of all methods in the interface (this definition was correct before Java 8, but the default implementation method of the interface was added after Java 8)

Abstract classes are special. abstract classes can define both member variables and abstract methods like interfaces to complete the details of methods by subclasses. If a class only implements partial method definitions in the interface, the class must be declared as an abstract class. This programming mode is often used. For example, Spring AbstractBeanFactory indirectly implements BeanFactory and common functions in other interfaces. Other methods are implemented by sub-classes. In our actual development, we often make an abstract interface for the Service and Dao, and then develop an abstract class to implement general functions, such as adding, deleting, modifying, querying, and turning pages in dao, for specific business content, it is implemented by sub-classes in the future.

Default Interface Method in Java 8

The default method allows the interface method to define the default implementation, and the subclass method can have this method and implementation without having to implement this method. As follows:

public interface DefaultFuncInter {    int getInt();    default String getString(){        return "Default String";    }}
Advantages of default methods

The main advantage of the default method is that it provides an interface extension method without damaging the existing code. If a new method needs to be extended for an interface that has been put into use, before JDK8, we must add the implementation of this method to all the implementation classes of this interface; otherwise, the compilation will fail. If the number of implementation classes is small and we have the modification permission, the workload may be small, but if there are many implementation classes or we do not have the permission to modify the code, it is very difficult to solve this problem. The default method provides an implementation. This implementation is used by default when it is not explicitly provided, so that the newly added interface will not destroy the existing code.

Another advantage of the default method is that this method is optional. sub-classes can be implemented by override or default based on different requirements. For example, we define several interfaces of a set, including adding, deleting, and modifying operations. If our implementation class 90% stores data in arrays, we can define the default implementation for these methods. For other non-array sets or other similar services, you can select the default method in the rewrite interface. (Because the interface does not allow member variables, this example is intended to show the advantages of the default method, but does not have the possibility of production.) For details, refer to the following code:

/*** Define the interface and include the default Implementation Method */public interface CollectionDemoInter {// Add default void addOneObj (Object object) {System. out. println ("default add");} // delete default void delOneObj (Object object) {System. out. println ("default del");} // update default void updateOneObj (Object object Object) {System. out. println ("default del");} // method String showMsg () required for interface definition ();}
/*** Add, delete, and modify an array-based collection implementation class using the default method */public class Collection4Array implements CollectionDemoInter {@ Override public String showMsg () {return null ;}}
/*** Special set. elements cannot be deleted */public class NodelCollection implements CollectionDemoInter {@ Override public String showMsg () {return null;} @ Override public void delOneObj (Object object) {System. out. println ("none del ");}}

Through the above code, you can clearly find that if you define the default method in the interface, the subclass does not need to implement this default implementation. If you have special requirements or needs, you can Override this implementation.

Note:
  • If a class implements two or more interfaces and multiple interfaces contain unified default methods, the compiler reports an error. In this case, we must make the subclass Override the method, otherwise the compilation will fail.
  • In all cases, the class implementation has a higher priority than the default Implementation of the interface, that is, the method defined in the class or the method in the parent class is used first.
  • If an interface inherits another interface and the two interfaces also contain the same default method, the version of the inherited interface has a higher priority. For example, if A extends the B interface, the test method in Class A is preferred.
  • By using super, You can explicitly reference the default Implementation of the inherited interface. The syntax is as follows: InterfaceName. super. methodName ().
Static Methods in the interface

Java 8 adds a function for the interface: defining one or more static methods. Similar to static methods in a class, static methods defined by interfaces can be called independently of any object. Therefore, when calling a static method, you do not need to implement an interface or an instance of the interface, that is, the method of calling a static method of the class is similar. Syntax example: interface name. Static Method Name.

Interface A {static String getName () {return "interface... ";}} Public class Test implements A {public static void main (String [] args) {System. out. println (A. getName ());}}

Note that the class or sub-interface implementing the interface does not inherit the static method in the interface. Static cannot be used together with default. Static methods are added to many interfaces in Java 8, such as the following code:

Public class Test {public static void test (List <String> list) {// use Comparator's static method list directly. sort (Comparator. comparing (String: length);} public static void main (String [] args) {List <String> list = Lists. newArrayList ("122", "2", "32"); test (list); for (String str: list) {System. out. println (str );}}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.