Java8 new Feature: The default method of interface and static method of interface

Source: Internet
Author: User
Tags object object

Definition of the interface

The role of an interface is to define the functionality that an instance of that type has, that is, what must be done, and does not need to be concerned about how the work is specific. An interface-defined method has no method body, and the interface does not allow the definition of an instance variable. If a class implements this interface, it must implement all methods that override the interface. The interface is as follows:

1  Public Interface myinterface{2     int getInt (); 3 }
Advantages of the interface

The interface is designed primarily to support the parsing of runtime dynamic methods. In general, in order to be able to invoke the method of another class from one class, these two classes need to exist at compile time, which makes the class system non-extensible. The purpose of the interface design is to enhance the extensibility of the class, as follows:

     Public Interface myinterface{        int  getInt ();    }
     Public class Implements myinterface{        @Override        publicint  getInt () {              return 6;        }    }
     Public classmain{        publicstaticvoid  main (string[] args) {            null ;             // obtain instances of Myinterfaceimpl or MYINTERFACEIMPL1 according to factory or other means             my.getint ();        }    }

In the code above, during compilation, the compiler cannot determine which of the implementation classes of the current "my" object. It is only possible to determine when the corresponding instance is created during run time, so that the polymorphic characteristics are better implemented.

The difference between a class and an interface
    • A member variable can be defined in a class, but a member variable is not allowed in the interface
    • None of the methods in the interface are specifically implemented (JAVA8 was previously correct, but the default implementation of the interface was added after JAVA8)

Abstract classes are special, and abstract classes can define both member variables and abstract methods, like interfaces, to complete the details of a method by subclasses. If a class simply implements a partial method definition in an interface, the class must be declared as an abstract class. This programming pattern is often used. For example, Spring's abstractbeanfactory indirectly implements common functions in beanfactory and other interfaces, and other methods are implemented by subsequent subclasses. In our actual development, but also often for the service and DAO to do an abstract interface, and then develop an abstract class, the common functions, such as adding and deleting DAO in the page and so on, for the business-specific content, the following sub-class implementation.

Default method for interface in JAVA8

The default method allows an interface method to define a default implementation, and the subclass method does not have to implement this method and can have the method and its implementation. As follows:

 Public Interface defaultfuncinter {    int  getInt ();     default String getString () {        return "Default String";    }}
Advantages of the default method

The main advantage of the default method is to provide a way to extend the interface without destroying the existing code. If an interface that has already been put into use needs to extend a new method, before JDK8, we must add the implementation of the method to all the implementation classes of that interface, or the compilation will fail. If the number of implementation classes is small and we have modified permissions, it may be less work, but if the implementation class is many or we do not have permission to modify the code, then it is difficult to solve. The default method provides an implementation that defaults to this implementation when it is not explicitly provided, so that the newly added interface does not break existing code.

Another advantage of the default method is that the method is optional, and subclasses can be implemented by override or by default, depending on the requirements. For example, we define a set of several, including the increment, delete, change, and so on, if our implementation class 90% is to save data in an array, then we can define the default implementation for these methods, and for other non-array collections or other similar business, you can selectively replicate the interface default method. (Because the interface does not allow member variables, this example is intended to illustrate the advantages of the default method and does not have production possibilities), specifically referencing the following code:

    /*** Define the interface and include the default implementation method*/     Public InterfaceCollectiondemointer {//Add default implementation    default voidAddoneobj (Object object) {System.out.println ("Default Add"); }    //Delete the default implementation    default voidDeloneobj (Object object) {System.out.println ("Default Del"); }    //Updating the default implementation    default voidUpdateoneobj (Object object) {System.out.println ("Default Del"); }    //interface definition requires implementation methodString showmsg ();}
    /**      * Array-based collection implementation classes, additions and deletions to use    the default method */public    classimplements    collectiondemointer {        @Override        public  String showmsg () {             returnnull;        }    }
    /**      * Special collection, do not allow deletion     of elements */public     classimplements   Collectiondemointer {        @Override        public  String showmsg () {            return  null;        }        @Override        publicvoid  deloneobj (Object object) {            System.out.println ( "None del");        }    }

With the above code, it is clear that if you define the default method in the interface, the subclass does not need to implement the default implementation, and if there are special needs or needs, you can override the implementation.

Need to be aware

If a class implements two or more interfaces, and more than one interface contains a unified default method, the compiler will make an error at this point. In this case, we have to let the subclass override the method, otherwise it cannot be compiled.

Java8 new Feature: The default method of interface and static method of interface

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.