Java基础编程题目——编写Cat类和Dog类继承Animal类

所谓继承:是指可以让某个类型的对象获得另一个类型的对象的属性的方法

public class text {
    public static void main(String[] args) {
        Cat cat = new Cat();
        Dog dog = new Dog();

        cat.setAge(6);            //继承会继承属性和方法
        cat.setName("大花猫");

        dog.setAge(8);
        dog.setName("大黑狗");

        cat.voice();
        cat.eat();
        cat.age();

        dog.voice();
        dog.eat();
        dog.age();
    }
}

class Animal {                //创建一个Animal类,封装属性,保留接口
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void age() {
        System.out.println(this.getName() + age + "岁");
    }
}

class Cat extends Animal {     //继承Animal类,extends关键字
    public void voice() {
        System.out.println(this.getName() + "喵喵叫");
    }

    public void eat() {
        System.out.println(this.getName() + "吃鱼");
    }

}

class Dog extends Animal {     //继承Animal类,extends关键字
    public void voice() {
        System.out.println(this.getName() + "汪汪叫");
    }

    public void eat() {
        System.out.println(this.getName() + "吃骨头");
    }
}
发布了203 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43479432/article/details/105085032