New features of Java 8: Default interface methods
Abstract: Starting from java8, the interface is not only a place where methods can only be declared. We can also give the method a default implementation when declaring the method. We call it the default interface method, so that all children that implement the interface Classes can hold a default implementation of this method.
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 (only by advancing with the times can we We should be pleased that it is immortal), but after so many years of development and iteration, the source code of Java has become a behemoth, and it will definitely not be easy to make a big move 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 interface, such as the
sort(Comparator<? super E> 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 confusing to think like this. Although we do not need to design JDK, we 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 the default interface method
The definition of the default interface method is very simple, just add a
default
key before the interface method definition Just use the following words:
public interface A { /** * 默认方法定义 */ default void method() { System.out.println("This is a default method!"); } }
When we define a default method like this, all subclasses that implement this interface indirectly hold this method. 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 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 things that are not every For methods that all subclasses need, we give it a default implementation to avoid meaningless implementations in subclasses (generally we will throw new UnsupportedException())
2. The default method is java. Multiple inheritance provides a new way (although we can only inherit one class, 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 there are two or more default methods with the same method signature in these interfaces, a conflict will occur, java8 definition The following three principles are used to resolve conflicts:
1. Explicitly declared methods in a class or parent class have a higher priority than all default methods
2. If rule 1 fails, select The default method with specific implementation that is closest to the current class
3. If rule 2 also fails, you need to explicitly specify the interface
The following is explained through several examples:
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!
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 what is actually called here is 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!
Example 2 adds a class D that implements interface A on the basis of the original interfaces A and B, and then class C inherits from D, and implements A and B. Although C is closer to D, because the specific implementation of D is in A, the default method in B is still the closest default implementation. According to rule 2, what is actually called here Is the default method of B.
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(); } }
In Example 3, interface B no longer inherits from interface A, so the default method is called in C at this time
method()
Distance interface The specific implementation distance of A and B is the same, and the compiler cannot determine it, so an error is reported. At this time, you need to specify it explicitly:
B.super.method()
.
The above is the content of the new feature of Java8, the default interface method. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

PHP8.3 released: Overview of new features As technology continues to develop and needs change, programming languages are constantly updated and improved. As a scripting language widely used in web development, PHP has been constantly improving to provide developers with more powerful and efficient tools. The recently released PHP 8.3 version brings many long-awaited new features and improvements. Let’s take a look at an overview of these new features. Initialization of non-null properties In past versions of PHP, if a class property was not explicitly assigned a value, its value

An in-depth analysis of the new features of PHP8 to help you master the latest technology. As time goes by, the PHP programming language has been constantly evolving and improving. The recently released PHP8 version provides developers with many exciting new features and improvements, bringing more convenience and efficiency to our development work. In this article, we will analyze the new features of PHP8 in depth and provide specific code examples to help you better master these latest technologies. JIT compiler PHP8 introduces JIT (Just-In-Time) compilation

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[

New features of php8 include JIT compiler, type deduction, named parameters, union types, properties, error handling improvements, asynchronous programming support, new standard library functions and anonymous class extensions. Detailed introduction: 1. JIT compiler, PHP8 introduces the JIT compiler, which is an important performance improvement. The JIT compiler can compile and optimize some high-frequency execution codes in real time, thereby improving the running speed; 2. Type derivation , PHP8 introduces the type inference function, allowing developers to automatically deduce the type of variables when declaring variables, etc.

[Interpretation of new features of Go language: To make programming more efficient, specific code examples are needed] In recent years, Go language has attracted much attention in the field of software development, and its simple and efficient design concept has attracted more and more developers. As a statically typed programming language, Go language continues to introduce new features to improve development efficiency and simplify the code writing process. This article will provide an in-depth explanation of the latest features of the Go language and discuss how to experience the convenience brought by these new features through specific code examples. Modular development (GoModules) Go language from 1

Overview of the new features of CSS3: How to use CSS3 to achieve transition effects CSS3 is the latest version of CSS. Among the many new features, the most interesting and practical one should be the transition effect. Transition effects can make our pages smoother and more beautiful during interaction, giving users a good visual experience. This article will introduce the basic usage of CSS3 transition effects, with corresponding code examples. transition-property attribute: Specify the CSS property transition effect that needs to be transitioned

Overview of the new features of CSS3: How to use CSS3 to achieve horizontally centered layout In web design and layout, horizontally centered layout is a common requirement. In the past, we often used complex JavaScript or CSS tricks to achieve this. However, CSS3 introduced some new features that make horizontally centered layouts simpler and more flexible. This article will introduce some new features of CSS3 and provide some code examples to demonstrate how to use CSS3 to achieve horizontally centered layout. 1. Use flexbox to layout fle
