Lambda expression of Java8 (default method)

Source: Internet
Author: User

Many development languages integrate function expressions into their collection libraries. This is less and easier to understand than the code required for looping. Take the following loop as an example:

for (int i = 0; i < list.size (); i++) System.out.println (List.get (i));

In fact there is a better way. API developers can provide a foreach method to apply a function to each element of the collection. Here is a simple call written in this way:

Package Java8test;import Java.util.arrays;import Java.util.list;public class T3 {public static void main (string[] args        {list<string> List = arrays.aslist ("A", "B", "C", "D", "E", "F");    Note This code List.foreach (system.out::p rintln); }}

If the collection library is completely redesigned, this will not be a problem. However, the collection Library of Java was designed many years ago, which poses a problem. If a new method, such as foreach, is added to the collection interface, then each custom class that implements the collection interface must implement the method. This is completely unacceptable in Java .

Java designers want to solve this problem once and for all by allowing the interface to contain methods with concrete implementations called default methods . These methods can be safely added to existing interfaces. Here we will explain the default method in detail. Note: In Java8, the Foreach method has been added to the Iterable interface (it is the parent interface of the collection interface). Suppose you have the following interfaces:

Interface Person {long getId ();    Note there is a default keyword, default String getName () {return "John Q. Public"; }}

The interface has two methods: An abstract method GetID, and a default method, GetName. Of course, the concrete class that implements the person interface must implement the GetID method, but it can choose to preserve the implementation of the GetName, or override it.

The default method ends a previous classic pattern. That is to provide an interface, and an abstract class that implements most or all of the interface's methods , for example: Collection/abstractcollection or Windowlistener/windowadapter. Now you just need to implement those methods in the interface.

if one of the interfaces defines a default method, and another parent class or interface defines a method with the same name, which one is chosen? languages like Scala and C + + may have a complex set of rules to address this ambiguity, but fortunately, the rules in Java are much simpler, as shown here:

    • Select a method in the parent class . If a parent class provides a concrete implementation method, the default method with the same name and parameters in the interface is ignored.

    • interface Conflicts . If a parent interface provides a default method, and another interface provides a method with the same name and parameter type, regardless of whether the method is the default method , you must resolve the conflict by overriding the method.

Let's take a detailed look at the second rule. Suppose that another interface also contains a method named GetName:

Interface named{default String getName () {return getclass (). GetName () + "_" + hashcode (); }}

What happens if you write a class that implements both interfaces at the same time?

Class Student implements Person,named {...}

This class inherits the GetName method that is provided by both the person and the named interface, but the implementations of the two methods are inconsistent. The Java compiler reports an error and is referred to the developer to resolve the conflict without automatically selecting one. In this case, you only need to provide a GetName method in the student class, and then choose to invoke the method in one of the interfaces as follows:

Interface person{long getId ();    Default String getName () {return "John Q. Public";    }}interface named{default String getName () {return getclass (). GetName () + "_" + hashcode ();    }}class Student implements person,named{@Override public long getId () {return 0;    } public String GetName () {//Note this sentence: Person.super.getName () return Person.super.getName (); }}

Now we assume that the named interface does not provide a default implementation of the GetName method:

Interface named{String getname ();}

If so, can the student class inherit the default method in the person interface? That might make sense, but the Java designers chose to do the same thing they did in order to stay unified. Two interfaces how conflict is not important, as long as an interface provides an implementation, the compiler reports an error, and the developer must manually resolve the conflict. Note: Of course, if none of the two interfaces provide a default implementation for the shared method, then we are back to Java8 and there is no conflict.

Now let's consider a class that inherits the parent class and implements an interface that has a method with the same name in the parent class and interface. For example, suppose that person is a class, and the student class is defined as follows:

Class Student extends person implements Named {...}

in this case, only the methods in the parent class will work, and any default methods in the interface will be ignored. In this example, student inherits the GetName method in the person class, regardless of whether the GetName method in the named interface is the default method . This is the " class first " rule. The "class first" rule guarantees Java7 compatibility. If you add a default method to the interface, it has no effect on the code previously written by Java8. Example:

Package java8test;public class t4 {    public static void  main (String[] args)  {        student stu =  new student ();         //class first, will print out: john q. public         system.out.println (Stu.getname ());     }} Class person{    public long getid () {         return 100l;    };    public string getname () {        return  "John q. public";     }}interface named{    default string getname () {         return getclass (). GetName ()  +  "_"  + hashcode ();     }}class&nbsP student extends person implements named{}

Lambda expression of Java8 (default method)

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: 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.