3月1号总结

7.2 接口
interface与class类似。主要用来定义类中所需包含的函数。

接口也可以继承其他接口,一个类可以实现多个接口。

7.2.1 接口的定义
接口中不添加修饰符时,默认为public

interface Role {
    public void greet();
    public void move();
    public int getSpeed();
}

7.2.2 接口的继承
每个接口可以继承多个接口

interface Hero extends Role {
    public void attack();
}

7.2.3 接口的实现
每个类可以实现多个接口

class Zeus implements Hero {
    private final String name = "Zeus";
    public void attack() {
        System.out.println(name + ": Attack!");
    }

    public void greet() {
        System.out.println(name + ": Hi!");
    }

    public void move() {
        System.out.println(name + ": Move!");
    }

    public int getSpeed() {
        return 10;
    }
}

7.2.4 接口的多态

class Athena implements Hero {
    private final String name = "Athena";
    public void attack() {
        System.out.println(name + ": Attack!!!");
    }

    public void greet() {
        System.out.println(name + ": Hi!!!");
    }

    public void move() {
        System.out.println(name + ": Move!!!");
    }

    public int getSpeed() {
        return 10;
    }
}

public class Main {
    public static void main(String[] args) {
        Hero[] heros = {new Zeus(), new Athena()};
        for (Hero hero: heros) {
            hero.greet();
        }
    }
}

 

posted @ 2023-03-01 21:08  lcz111  阅读(21)  评论(0)    收藏  举报