Home Java javaTutorial New features of Java8 - default interface method

New features of Java8 - default interface method

Nov 22, 2016 pm 02:41 PM
java8

1. The background of introducing default interface methods

 Java8 can be regarded as the version that has changed the most in the iterative process of Java version updates (we should be happy to keep pace with the times to survive), but after so many years of development And iteration, the source code of Java is already a giant, and it will definitely not be easy to work on such a huge volume. So when I saw the default interface methods of Java 8 for the first time, my first feeling was that this was a hole dug by Java designers before they filled it.
From the previous explanations, we know that java8 has added many methods to the existing interfaces, such as the sort(Comparator c) method of List. If you follow the design ideas of interfaces before Java 8, when adding a method declaration to an interface, the class that implements the interface must add a corresponding implementation for the newly added method. Considering compatibility, this is not advisable, so it is a pitfall, and new features require adding some new methods to the interface. In order to have the best of both worlds, the designers of Java8 proposed the default interface method the concept of.
In this way, the default interface method seems to be developed for API designers, which is still far away from us ordinary developers. It is a bit TuSimple to think like this. Although we do not need to design jdk, we are still in the daily development process There will still be a need to provide APIs for other business parties to call. When we update our APIs, we can use the default method to provide more advanced functions while maintaining compatibility.

2. Definition of default interface method

  The definition of default interface method is very simple, just add a default keyword before the method definition of the interface, as follows:

public interface A {    /**
     * 默认方法定义
     */
    default void method() {
        System.out.println("This is a default method!");
    }

}
Copy after login

When we define a default method like this, all implementations Subclasses of this interface all hold this method indirectly. Or you may feel like me that interfaces and abstract classes are becoming more and more similar, indeed, but there are still the following differences between them:

  1. A class can only inherit one class, but it can implement multiple interfaces

  2. Abstract classes can define variables, but interfaces cannot

     In addition to solving the problems we mentioned above, abstraction also has the following benefits:

    1. For some methods that are not required by every subclass, we give it a default implementation , thus avoiding our meaningless implementation in subclasses (generally we will throw new UnsupportedException())

    2. The default method provides a new way for multiple inheritance in Java (although we can only inherit one class, but We can implement multiple interfaces, and now interfaces can also define default methods)


3. Conflicts and their solutions

Because a class can implement multiple interfaces, when a class implements multiple Interfaces, and conflicts will occur when there are two or more default methods with the same method signature in these interfaces. Java8 defines the following three principles to resolve conflicts:

1. For methods explicitly declared in a class or parent class, their The priority is higher than all default methods


2. If rule 1 fails, select the default method with specific implementation closest to the current class


3. If rule 2 also fails, you need to show

The following are several examples to illustrate:

Example 1

public interface A {    /**
     * 默认方法定义
     */
    default void method() {
        System.out.println("A's default method!");
    }

}public interface B extends A {    /**
     * 默认方法定义
     */
    default void method() {
        System.out.println("B's default method!");
    }

}public class C implements A, B {    public static void main(String[] args) {        new C().method();
    }

}// 输出:B's default method!
Copy after login

Here, because interface B is closer to C than A, and the method of B is a specific default implementation, according to rule 2, so this What is actually called is the default method of interface B

Example 2

public class D implements A {
}public class C extends D implements A, B {    public static void main(String[] args) {        new C().method();
    }

}// 输出:B's default method!
Copy after login

Example 2 adds a class D that implements interface A on the basis of the original interfaces A and B. Then class C inherits from D and implements A. and B. Although C is closer to D here, because the specific implementation of D is in A, the default method in B is still the closest default implementation. According to rule 2, the default method of B is actually called here. .

Example 3

// A接口不变public interface B {    /**
     * 默认方法定义
     */
    default void method() {
        System.out.println("B's default method!");
    }

}public class C implements A, B {    @Override
    public void method() {        // 必须显式指定
        B.super.method();
    }    public static void main(String[] args) {        new C().method();
    }

}
Copy after login

例3中接口B不再继承自接口A,所以此时C中调用默认方法method()距离接口A和B的具体实现距离相同,编译器无法确定,所以报错,此时需要显式指定:B.super.method()。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
How to calculate date one year ago or one year later in Java 8? How to calculate date one year ago or one year later in Java 8? Apr 26, 2023 am 09:22 AM

Java8 calculates the date one year ago or one year later using the minus() method to calculate the date one year ago packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args ){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

How to calculate date one week later using Java 8? How to calculate date one week later using Java 8? Apr 21, 2023 pm 11:01 PM

How to calculate the date one week later in Java8 This example will calculate the date one week later. The LocalDate date does not contain time information. Its plus() method is used to add days, weeks, and months. The ChronoUnit class declares these time units. Since LocalDate is also an immutable type, you must use variables to assign values ​​after returning. packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo08{publicstaticvoidmain(String[

What are the date comparison methods in Java8? What are the date comparison methods in Java8? Apr 29, 2023 pm 04:46 PM

Java8 Date Comparison Methods In Java8, you can use the new isBefore(), isAfter(), isEqual() and compareTo() to compare LocalDate, LocalTime and LocalDateTime. The following example to compare two java.time.LocalDate@TestvoidtestDateCompare4() throwsParseException{DateTimeFormattersdf=DateTimeFormatter.ofPattern("yyyy-MM-dd&quot

How to use the Clock class in Java8 How to use the Clock class in Java8 Apr 25, 2023 pm 03:37 PM

Java8's Clock class Java8 adds a Clock class for obtaining the current timestamp, or date and time information in the current time zone. Where System.currentTimeInMillis() and TimeZone.getDefault() were used before, they can be replaced by Clock. packagecom.shxt.demo02;importjava.time.Clock;publicclassDemo10{publicstaticvoidmain(String[]args){//Returnsthecurrenttimebase

How to deal with time zones in Java8 How to deal with time zones in Java8 Apr 27, 2023 pm 09:22 PM

Handling time zones in Java 8 Java 8 not only separates date and time, but also separates time zones. There are now a series of separate classes such as ZoneId to handle specific time zones and ZoneDateTime to represent time in a certain time zone. This was done by the GregorianCalendar class before Java8. The following example shows how to convert the time in this time zone to the time in another time zone. packagecom.shxt.demo02;importjava.time.LocalDateTime;importjava.time.ZoneId;importjava.time.ZonedDateT

How to get the current timestamp in Java8 How to get the current timestamp in Java8 May 01, 2023 am 11:46 AM

Get the current timestamp in Java8. The Instant class has a static factory method now() that returns the current timestamp, as shown below: packagecom.shxt.demo02;importjava.time.Instant;publicclassDemo16{publicstaticvoidmain(String[]args) {Instanttimestamp=Instant.now();System.out.println("Whatisvalueofthisinstant"+timestamp.t

How to get today's date in Java8 How to get today's date in Java8 May 01, 2023 pm 06:49 PM

Get today's date in Java8 LocalDate in Java8 is used to represent today's date. Unlike java.util.Date, it only has dates and does not include time. Use this class when you only need to represent dates. packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo01{publicstaticvoidmain(String[]args){LocalDatetoday=LocalDate.now();System.out.println("Today’s date:&q

How to use predefined formatting tools to parse or format dates in Java8 How to use predefined formatting tools to parse or format dates in Java8 Apr 28, 2023 pm 07:40 PM

How to use predefined formatting tools to parse or format dates in Java8 packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.format.DateTimeFormatter;publicclassDemo17{publicstaticvoidmain(String[]args){StringdayAfterTommorrow="20180205 ";LocalDateformatted=LocalDate.parse

See all articles