Animal类代码:

package domain;

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

public Animal() {
}

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

public abstract void eat();

public String getName() {
    return name;
}

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

public int getAge() {
    return age;
}

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

}

Cat类代码:

package domain;

public class Cat extends Animal { private int lovely;

public Cat() {
}

public Cat(String name, int age, int lovely) {
    super(name, age);
    this.lovely = lovely;
}

@Override
public void eat() {
    System.out.println(getName() + " is eating fish.");
}

public void catchMouse() {
    System.out.println(getName() + " is catching mouse.");
}

public int getLovely() {
    return lovely;
}

public void setLovely(int lovely) {
    this.lovely = lovely;
}

}

Dog类代码:

package domain;

public class Dog extends Animal { private double weight;

public Dog() {
}

public Dog(String name, int age, double weight) {
    super(name, age);
    this.weight = weight;
}

@Override
public void eat() {
    System.out.println(getName() + " is eating meat.");
}

public void watch() {
    System.out.println(getName() + " is watching.");
}

public double getWeight() {
    return weight;
}

public void setWeight(double weight) {
    this.weight = weight;
}

}

测试类代码:

import domain.Animal; import domain.Cat; import domain.Dog;

public class AnimalTest { public static void main(String[] args) { Cat cat = new Cat("Tom", 2, 90); Dog dog = new Dog("Jerry", 3, 10.5);

    System.out.println("猫的姓名:" + cat.getName());
    System.out.println("猫的年龄:" + cat.getAge());
    System.out.println("猫的可爱度:" + cat.getLovely());
    cat.eat();
    cat.catchMouse();

    System.out.println("狗的姓名:" + dog.getName());
    System.out.println("狗的年龄:" + dog.getAge());
    System.out.println("狗的体重:" + dog.getWeight());
    dog.eat();
    dog.watch();
}

}

输出结果:

猫的姓名:Tom 猫的年龄:2 猫的可爱度:90 Tom is eating fish. Tom is catching mouse. 狗的姓名:Jerry 狗的年龄:3 狗的体重:10.5 Jerry is eating meat. Jerry is watching

采用抽象的思想编写猫和狗的案例在测试类中进行测试【需求】:分析猫类和狗类找到猫类和狗类当中的共性内容抽取出一个父类用继承的方式编写一个父类Animal 两个子类猫类Cat和狗类Dog;【分析】:猫类 成员变量:姓名年龄 构造方法:无参、全参 成员方法:getset方法、吃饭、抓老鼠狗类 成员变量:姓名年龄 构造方法:无参、全参 成员方法:getset方法、吃

原文地址: https://www.cveoy.top/t/topic/em4Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录