java 程序定义一个动物类(Animal)。属性(age、weight);方法(叫meow)、吃eat()、设置年龄setAge(),得到年龄getAge()等。然后再派生出两个子类狗(Dog)和奶牛(Cow),再根据各自特性添加成员变量和成员方法。设计测试用例进行测试。
时间: 2023-06-19 11:03:51 浏览: 1358
下面是实现动物类及其子类的Java代码:
```java
// Animal.java
public class Animal {
private int age;
private double weight;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
public void eat() {
System.out.println("Animal is eating.");
}
public void meow() {
System.out.println("Animal is meowing.");
}
}
// Dog.java
public class Dog extends Animal {
private String breed;
public void setBreed(String breed) {
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void bark() {
System.out.println("Dog is barking.");
}
}
// Cow.java
public class Cow extends Animal {
private boolean isMilkProducing;
public void setIsMilkProducing(boolean isMilkProducing) {
this.isMilkProducing = isMilkProducing;
}
public boolean getIsMilkProducing() {
return isMilkProducing;
}
public void moo() {
System.out.println("Cow is mooing.");
}
}
```
下面是测试用例:
```java
// Test.java
public class Test {
public static void main(String[] args) {
Animal animal = new Animal();
animal.setAge(3);
animal.setWeight(10.5);
System.out.println("Animal age: " + animal.getAge());
System.out.println("Animal weight: " + animal.getWeight());
animal.eat();
animal.meow();
Dog dog = new Dog();
dog.setAge(2);
dog.setWeight(15.0);
dog.setBreed("Golden Retriever");
System.out.println("Dog age: " + dog.getAge());
System.out.println("Dog weight: " + dog.getWeight());
System.out.println("Dog breed: " + dog.getBreed());
dog.eat();
dog.meow();
dog.bark();
Cow cow = new Cow();
cow.setAge(5);
cow.setWeight(500.0);
cow.setIsMilkProducing(true);
System.out.println("Cow age: " + cow.getAge());
System.out.println("Cow weight: " + cow.getWeight());
System.out.println("Cow is milk producing: " + cow.getIsMilkProducing());
cow.eat();
cow.meow();
cow.moo();
}
}
```
运行结果如下:
```
Animal age: 3
Animal weight: 10.5
Animal is eating.
Animal is meowing.
Dog age: 2
Dog weight: 15.0
Dog breed: Golden Retriever
Animal is eating.
Animal is meowing.
Dog is barking.
Cow age: 5
Cow weight: 500.0
Cow is milk producing: true
Animal is eating.
Animal is meowing.
Cow is mooing.
```
阅读全文