Animal类的继承与接口的例子 | java

发布于 2021-07-10  22 次阅读


我的csdn文章链接:https://blog.csdn.net/LLLLQZ/article/details/116330123

1、前言

这是一个关于继承与接口的简单例子

2、题目

实现下面图示
在这里插入图片描述

3、代码实现

代码我都放到了ANIMAL包里
在这里插入图片描述

Animal类

package ANIMAL;

public abstract class Animal {
    public int legs;

    public Animal(int legs)
    {
        this.legs=legs;
    }

    public void walk()
    {

    }

    public abstract void eat();
}

Pet类

package ANIMAL;

public interface Pet {
    public String getName();
    public void setName(String name);
    public void play();
}

Spider类

package ANIMAL;

public class Spider extends Animal{

    public Spider()
    {
        super(8);
    }

    public void eat()
    {
        System.out.println("spider eat");
    }
}

Cat类

package ANIMAL;

public class Cat extends Animal implements Pet{
    private String name;

    public Cat(String name)//一定要给父类传参,因为父类的构造函数有参数
    {
        super(4);
        this.name = name;
    }

    public Cat()
    {
        super(4);
        this.name="";
    }

    public String getName()
    {
        return this.name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void play()
    {
        System.out.println("Cat is playing");
    }

    public void eat()
    {
        System.out.println("cat eat");

    }
}

Fish类

package ANIMAL;

public class Fish extends Animal implements Pet{

    private String name;

    public Fish()
    {
        super(0);
        this.name = "";
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name=name;
    }

    @Override
    public void play()
    {
        System.out.println("Fish is playing");
    }

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

测试用的Main类

package ANIMAL;

public class Main {

    public static void main(String[] args) {
        Cat cat1=new Cat("黑猫");
        Spider spider1=new Spider();
        Fish fish1=new Fish();

        System.out.println("cat name:"+cat1.getName());
        cat1.eat();
        cat1.play();

        fish1.setName("鲈鱼");
        System.out.println("fish name:"+ fish1.getName());
        fish1.eat();
        fish1.play();
        fish1.walk();

        spider1.eat();

        Pet pet1=new Cat("白猫");
        System.out.println(pet1.getName());

    }

}

运行结果
在这里插入图片描述

4、结语

如果有哪里写错了的,麻烦评论区告诉我,谢谢大家阅读