SoFunction
Updated on 2025-04-13

How to use default in java interface

The default (default) usage of java interface

definition

There is a special method in Java interface called the default method.

The default method in the interface has the following characteristics:

  • default methodThere may be a method body.
  • Normal methods in the interface must be rewritten by the implementation class; the default methods may not be rewritten by the implementation class.

effect

The specific role of this feature in practice is:

  • When we expand our business, we need to add new methods to the interface.
  • If the newly added method is written as a normal method, then the method needs to be rewrited in all implementation classes of the interface.
  • If the new method is defined asdefaultType, there is no need to override the default in all implementation classesMethod, which implementation class needs to add this method, it will be implemented in which implementation class.

However, it is necessary to note under what circumstances the use of default will be limited

  • If an implementation class implements only one interface, you can do not need to override the default methods in the interface.
  • If an implementation class implements multiple interfaces, and the default methods of two interfaces are the same in these interfaces, then the default methods must be overridden in the implementation class.

The default method can be called directly through the interface implementation object and can be rewritten by the interface implementation class.

interface test{
       default public void print() {
              ("This is a interface with default");
       }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.