“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

The default modifier

Why have a default method?

When an interface needs to add a method, then all of its implementation classes need to implement that method, which can change a lot.

With the defalut modifier, methods can be implemented directly in the interface. This method is implemented by default by all implementation classes and can be overridden by implementation classes that need to implement this method.

example

In the interface, you can implement the method body using the defalut modifier

public interface defalutInterface { void getName(); // Use default to implement method body default void getNames() {system.out.println ("name"); }}Copy the code

The implementation class can inherit and use the default modified method without implementing it.

public static void main(String[] args) { defaultClass defaultClass = new defaultClass(); // DefaultClass.getNames () can be called directly; // output name}}Copy the code

Implementation classes can override methods

@Override public void getNames() { System.out.println("className"); } // Output from classNameCopy the code

Conflict problem

Public interface animals {default void eat() {system.out.println (" animals eat "); }} public interface people {default void eat() {system.out.println (" people eat "); }}Copy the code

When implementing multiple interfaces, each of these interfaces has a default method of the same name. Then the system will not know which one to implement, error, need to rewrite

This choice situation is similar to the choice of multiple inheritance (of course Java does not allow multiple inheritance, and there may be some consideration for this);

Practice class implementation of the same problem, need to rewrite

priority

1. The default method takes precedence over the common method of the interface: If the defalut method name of the subinterface is the same as the common /default method name of the parent interface, the parent method becomes invalid

2. The parent method of a class takes precedence over the default method of the interface: When the parent method has the same name as the default method of the interface, the parent method takes precedence.

To sum up: implementation methods take precedence over abstract methods, implementation classes take precedence over interfaces