接口(interface)

接口(interface)

如何定义接口

简单点,是这个流程

定义一个接口
//Myinterface.java

package cn.textInterface;

public interface Myinterface {
    //接口中只有:常量、抽象方法!
    /*public static final 接口中常量定义时,写或不写都是这样*/String MAX_Greead="Boss";    //常量
    int MAX_Speed=120;
    
    /*public abstract*/void test01();      //抽象方法
    public int test02(int a,int b);
}

实现这个接口
//Myclass.java

package cn.textInterface;

public class Myclass implements Myinterface {

    @Override
    public void test01() {
        System.out.println("test01");
        
    }

    @Override
    public int test02(int a, int b) {
        System.out.println("test02");
        return a+b;
    }

}

小示例

Flyable.java.

package cn.textInterface;

public interface Flyable {
    int MAX_SPEED=11000;
    int MIN_HEIGHT=1;
    void fly();
}
interface Attack{
    public void attack();
}
class Plane implements Flyable{

    @Override
    public void fly() {
        System.out.println("飞机在天上飞");
        
    }
    
}
class Man implements Flyable{

    @Override
    public void fly() {
        System.out.println("你飘了");
        
    }
    
}
class stone implements Flyable,Attack{
    String a;
    @Override
    public void fly() {
        System.out.println("扔起来飞");
    }

    @Override
    public void attack() {           //一个类可以实现多个接口
        System.out.println(a+"石头攻击");
    }
    
}

Test.java

package cn.textInterface;

public class Test {
    public static void main(String[]args) {
        Flyable f=new stone(); //父类引用指向子类对象
        Attack a=new stone();
        f.fly();
        a.attack();
        stone ff=(stone)f;
        ff.a="sun";          //调用子类中的变量必须强制类型转换为stone型,此时stone的方法变量,均可调用。
        ff.attack();
        ff.fly();
        
    }
}

接口实现多继承

Iterface.java

package cn.textInterface;

public interface Iterface {
    public abstract void aaa();
}
interface Interface2{
    public abstract void bbb();
}
interface Interface3 extends Iterface,Interface2{   //接口间实现多继承。
    void ccc();
}
class Testclass implements Interface3{     //如果要实现Interface3 ,要写三个方法。

    @Override
    public void aaa() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void bbb() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void ccc() {
        // TODO Auto-generated method stub
        
    }
    
}

 

posted on 2019-07-15 18:44  Mentality  阅读(308)  评论(0编辑  收藏  举报