帮我写出以下代码,Create a class Animal with the following UML specification: +-----------------------+ | Animal | +-----------------------+ | - name: String | +-----------------------+ | + Animal(String name) | | + getName(): String | | + getLegs(): int | | + canFly(): boolean | | + testAnimal(): void | +-----------------------+ where the name instance variable stores a name for the animal, the getLegs method returns as result the animal's number of legs, and the canFly method returns as result a boolean indicating whether the animal can fly or not. The testAnimal method is static. Should the getLegs method be abstract? Why or why not? Should the canFly method be abstract? Why or why not? Should the Animal class be abstract? Why or why not? What kinds of tests can you write inside the testAnimal method?
时间: 2023-06-03 21:05:25 浏览: 106
多态练习,一个求动物类的程序代码
以下是代码实现:
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getLegs() {
return 0;
}
public boolean canFly() {
return false;
}
public static void testAnimal() {
// your test cases here
}
}
在这个Animal类中,name实例变量存储动物的名称,getLegs方法返回动物的腿的数量,canFly方法返回一个布尔值,指示动物是否能够飞行。testAnimal方法是静态的,通过测试Animal类的实例化对象,检验这个类定义是否符合预期。可以编写以下测试:
Animal lion = new Animal("lion");
assertEquals("lion", lion.getName());
assertEquals(4, lion.getLegs());
assertFalse(lion.canFly());
Animal bird = new Animal("bird");
assertEquals("bird", bird.getName());
assertEquals(2, bird.getLegs());
assertTrue(bird.canFly());
在这个示例中,getLegs和canFly方法不应该是抽象的,因为它们可以具有默认实现。Animal类也不应该是抽象的,因为有了默认行为。
阅读全文