The default method in Java

The default method is JDK8 new features, means that the interface may also provide a specific method, and as before, can only provide an abstract method, Mortal this interface, adds a default method r, this method has achieved the body, and is declared to default, as the following code:

This is Mortal interfaces, line 5, line 3 to the method defaults method thereof

1 public interface Mortal {
2     public void die();
3     default public void r() {
4         System.out.println("牛皮");
5     }
6 
7 }

Here is ADHero class that implements the above interfaces, call the method of the seventh default behavior

1 public class ADHero implements Mortal {
2     public void die() {
3         System.out.println("ad英雄死了");
4     }
5     public static void main(String[] args) {
6         ADHero a=new ADHero();
7         a.r();
8     }
9 }

Assuming no default method of this mechanism, so if you want to add a new method Mortal revive, then all Mortal class that implements the interface, you need to make changes. But after the introduction of the default method, the original class, do not need to make any changes, and also get the default method. By this means, it can be a good expansion of new classes, and do not affect the original class.

Guess you like

Origin www.cnblogs.com/z-cg/p/12243779.html