用java代码 定义动物类,包含 属性有名称,重量,年龄等,方法有:叫唤。实现其的子类(狗,猫等)不同的叫唤行为,并在测试类中输出。
时间: 2024-05-23 11:14:45 浏览: 78
// 定义动物类
public class Animal {
private String name;
private double weight;
private int age;
public Animal(String name, double weight, int age) {
this.name = name;
this.weight = weight;
this.age = age;
}
public void call() {
System.out.println(name + "正在叫唤...");
}
}
// 定义狗类
public class Dog extends Animal {
public Dog(String name, double weight, int age) {
super(name, weight, age);
}
@Override
public void call() {
System.out.println(getName() + "正在汪汪叫...");
}
}
// 定义猫类
public class Cat extends Animal {
public Cat(String name, double weight, int age) {
super(name, weight, age);
}
@Override
public void call() {
System.out.println(getName() + "正在喵喵叫...");
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Animal animal1 = new Animal("动物", 10, 1);
animal1.call();
Animal dog1 = new Dog("小狗", 5, 2);
dog1.call();
Animal cat1 = new Cat("小猫", 2, 1);
cat1.call();
}
}
// 输出结果
// 动物正在叫唤...
// 小狗正在汪汪叫...
// 小猫正在喵喵叫...
阅读全文