JAVA --Interface and inheritance (11) default method

What is the default method

The default method is a new feature of JDK8, which means that the interface can also provide specific methods, unlike before, which can only provide abstract methods

The Mortal interface adds a default method revive, which has an implementation body and is declared as default

package charactor;
 
public interface Mortal {
    
    
    public void die();
 
    default public void revive() {
    
    
        System.out.println("本英雄复活了");
    }
}

Why is there a default method

Assuming there is no such mechanism as the default method, if you want to add a new method revive to Mortal, then all classes that implement the Mortal interface need to be changed.

But after introducing the default method, the original class does not need to be changed, and the default method can still be obtained

By this means, the new class can be extended well without affecting the original class

Exercise-default method ⭐⭐⭐⭐Add
a default method attack() to the AD interface and a default method attack()
to the AP interface.
Q: ADAPHero implements both AD and AP interfaces, so when the ADAPHero object calls attack(), Which interface of attack() is called?

Answer: Report an error directly
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_17802895/article/details/108694885
Recommended