Why do you want to draw the default method in Java 8

Source: Internet
Author: User

Original

The default method is a new introduction in Java 8, which allows the interface in addition to an abstract method, but also can hold the implementation of the method, which is not the same as the previous version of Jdk8, why do you want to do this?

Take the list interface example, in the old system before Java 8, a developer wrote a class Definedlist himself, which inherits from the list interface.

There is no doubt that Definedlist will implement all the abstract methods in the list interface.

In Java 8, Oracle feels that it can actually make lists do more things, such as the list data that is commonly used in development, so they want to add a sort method.

However, because the list is an interface, adding an abstract method to the interface will allow its implementation class to increase the implementation of the sort method, in addition to the implementation of the list in Java, such as arryalist,linkedlist need to add the Sort method, We also need to add this sort to the definedlist we write ourselves.

If Java in the old system is upgraded from 7 to 8, then the code will be error-bound.

In order to solve the Java version backward compatibility problem, the implementation body is added to the sort method in list.

@SuppressWarnings ({"Unchecked", "Rawtypes"})    default void sort (comparator<? super E> C) {        object[] a = This.toarray ();        Arrays.sort (A, (Comparator) c);        listiterator<e> i = This.listiterator ();        for (Object e:a) {            i.next ();            I.set ((e) e);        }    

If this time again by Java7 upgrade to Java8, then Definedlist will inherit the sort method, Definedlist will not error, so you can perfectly solve the problem of Java backward compatibility.

Why do you want to draw the default method in Java 8

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.