接口

接口

1. 接口的意义

解决java不能多继承问题,一个类只能有一个父类 但是可以实现多个接口

查看代码
interface IFly {
    void fly();
}

interface ISwim {
    void swim();
}

interface IRun {
    void run();
}

class Animal {
    public String name;

    public Animal(String name) {
        this.name = name;
    }
}

class Dog extends Animal implements ISwim,IRun {
    public Dog(String name) {
        super(name);
    }

    @Override
    public void swim() {
    System.out.println(this.name + "正在用4条狗腿游泳");
    }

    @Override
    public void run() {
        System.out.println(this.name + "正在用4条狗腿跑");
    }
}

class Bird extends Animal implements IFly,IRun {
    public Bird(String name) {
        super(name);
    }

    @Override
    public void fly() {
        System.out.println(this.name + "正在用翅膀飞");
    }

    @Override
    public void run() {
        System.out.println(this.name + "正在用2条鸟腿跑");
    }
}

class Test {
    public static void funcRun(IRun iRun) {
        iRun.run();
    }

    public static void main(String[] args) {
        funcRun(new Dog("大黄狗"));
        funcRun(new Bird("布谷鸟"));
    }
}

 

2. 接口中的细节

1.  在接口中定义的成员变量 默认都是用public static final修饰的常量,接口中的抽象方法 默认都是用public abstract修饰的

 

2.  接口中的方法默认都是抽象方法 不能有具体的实现,如果要有具体实现 必须用default 或者 static修饰

interface Test {
    
    public default void test2() {

    }

}

 

3. 接口不能被实例化

interface Test {

    void test2();

}

class Main {
    public static void main(String[] args) {
        // 报错 !
        Test test = new Test();
    }
}

 

4. 实现接口的类,必须重写接口中所有的抽象方法

如果不重写接口中所有的抽象方法,加abstract设计为抽象类

interface IShape {
    void draw();
}

// 报错 !
class A implements IShape {

}

public class Test {
    public static void main(String[] args) {

    }
}
interface IShape {
    void draw();
}

abstract class A implements IShape {

}

public class Test {
    public static void main(String[] args) {

    }
}

 

5. 类与接口关系用implements 关联

查看代码
 interface IShape {
    void draw();
}

class Rect implements IShape {
    @Override
    public void draw() {
        System.out.println("画矩形");
    }
}

class Cycle implements IShape {
    @Override
    public void draw() {
        System.out.println("画圆圈");
    }
}

class Flower implements IShape {
    @Override
    public void draw() {
        System.out.println("画❀");
    }
}

public class Test {
    public static void func(IShape iShape) {
        iShape.draw();
    }

    public static void main(String[] args) {
        
        func(new Rect());
        func(new Cycle());
        func(new Flower());
    }
}

 

6. 接口与接口的关系用extends关联

查看代码
 interface IFly {
    void fly();
}

interface ISwim {
    void swim();
}

interface IRun {
    void run();
}

interface IAmphious extends ISwim,IRun {
    void test();
}

class Frog implements IAmphious {
    
    @Override
    public void swim() {
        
    }

    @Override
    public void run() {

    }

    @Override
    public void test() {

    }
}

 

posted @ 2024-03-27 21:06  qyx1  阅读(23)  评论(0)    收藏  举报