接口

接口(interface)

接口就是规范,定义就是一组规则,体现现实世界中“如果你是……则必须能……”,如:如果你是汽车,则必须能跑。

接口的本质是契约,就像我们的法律一样,必须遵守。

面向对象的精髓,是对对象的抽象,最能体现这一点的是接口。

接口就是比“抽象类”还要“抽象”的“抽象类”。专业地实现了:规范和具体实现的分离。

区别:

l  普通类:具体实现。

l  抽象类:具体实现,规范(抽象方法)

l  接口:规范(JDK8以后可有一些静态方法和默认方法)

package com.sanyuan.interface1;

public class SuperMan implements Volant,Honest {

    @Override
    public void fly() {
        // TODO Auto-generated method stub
        System.out.println("横着飞!!!");
        
    }

    @Override
    public void stop() {
        // TODO Auto-generated method stub
        System.out.println("竖着停!!!");
        
    }

    @Override
    public void helpOther() {
        // TODO Auto-generated method stub
        System.out.println("哪里call我,飞哪里!");
    }
    
    public static void main(String[] args) {
        SuperMan s1 = new SuperMan();
        s1.fly();
        s1.helpOther();
        
        Volant v1 =new SuperMan();
        v1.stop();
        
        Honest h1 = (Honest)s1;
        h1.helpOther();
        
    }
    
}
package com.sanyuan.interface1;

/**
 * 飞行器接口
 * @author huang
 *
 */
public interface Volant {
    //飞行器飞行高度,单位:公里
    /*public static final*/ int FLY_HEIGHT = 1000;
    //飞行方法,飞行器起飞
    /*public abstract*/ void fly();
    //停止方法,悬停或降落
    void stop();

}

/**
 * 善良接口
 * @author huang
 *
 */
interface Honest{
    void helpOther();
}

 

posted @ 2021-07-19 22:31  风中一抹黄  阅读(80)  评论(0)    收藏  举报