Java self - interface inherits the default method

The default method

Step 1: What is the default method

The default method is JDK8 new features, refer to the interface may also provide a specific method, but unlike before, can only provide an abstract method

Mortal This interface adds a default method revive, this method has achieved body, and is declared to default

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

Step 2: Why is there a default method

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

Exercise : The default method

As AD interface adds a default method of attack ()
for the AP interface also adds a default method of attack ()
Q: ADAPHero while achieving AD, AP interface, ADAPHero object calls attack () when it is attack which interface call () ?

The answer :

package charactor;
 
public class ADAPHero extends Hero implements AD,AP,Mortal{
 
    @Override
    public void magicAttack() {
        // TODO Auto-generated method stub
         
    }
 
    @Override
    public void physicAttack() {
        // TODO Auto-generated method stub
         
    }
 
    @Override
    public void die() {
        System.out.println(name+ " 这个混合英雄挂了");
    }
 
    //作为同时继承了AD和AP中的 默认方法attack,就必须在实现类中重写该方法
    //从而免去到底调用哪个接口的attack方法这个问题
    @Override
    public void attack() {
        //
        System.out.println("这个ADAPHero自己的attack方法");
    }
 
}

Guess you like

Origin www.cnblogs.com/jeddzd/p/11582187.html