实现多个接口

实现多个接口

abstract class Animal{
    public String name;
    public int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public abstract void eat();
}
//1 实现多个接口,把这个接口也给狗和鸟了
interface IRunning{
    void run();
}
//2
interface IFlying{
    void fly();
}

class Dog extends Animal implements IRunning{
    public Dog(String name, int age) {
        super(name, age);
    }

    @Override
    public void eat() {
        System.out.println(name+"正在吃狗粮!");
    }
    //1
    @Override
    public void run() {
        System.out.println(name+"正在跑!");
    }
}
class Bird extends Animal implements IRunning,IFlying{
    public Bird(String name, int age) {
        super(name, age);
    }

    @Override
    public void eat() {
        System.out.println(name+"正在吃鸟粮!");
    }
//1
    @Override
    public void run() {
        System.out.println(name + "正在用两条细细的腿跑!");
    }
//2
    @Override
    public void fly() {
        System.out.println(name+"正在用两个翅膀飞!");
    }
}
//3 机器人实现了接口跑
class Robot implements IRunning{
    @Override
    public void run() {
        System.out.println("机器人在跑!");
    }
}
public class Test {
    //3
    public static void main(String[] args) {
        walk(new Robot());//机器人在跑!
    }



    //1 这里是实现跑:用接口实现的
    public static void walk(IRunning iRunning){
        iRunning.run();
    }
    //这里是实现吃:用继承实现的
    public static void func1(Animal animal){
        animal.eat();
    }

    public static void main1(String[] args) {
        walk(new Dog("狗子",10));//狗子正在跑!
        walk(new Bird("小鸟",3));//小鸟正在用两条细细的腿跑!
        func1(new Dog("狗子",10));//狗子正在吃狗粮!
        func1(new Bird("小鸟",3));//小鸟正在吃鸟粮!
    }
}

你可能感兴趣的:(java,开发语言)