Java代码实现: 简单多态问题 问题描述 编程实现右图的类图,并编写 一段程序来测试。 (1)可自行添加其他的成员变量和 成员方法 (2) 各个子类的introduceSelf方 法打印出子类的类名。 (3)本题的重点是测试程序的编 写,需要测试各种情形,如单个对象、数组化(即定义一个数组,包含不同子类的对象)和 参数化(定义一个函数,它的实参可以是不同子类的对象)
时间: 2024-03-18 08:39:14 浏览: 118
以下是Java代码实现,包含了类的继承、多态和数组化:
```
// Animal 类
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void introduceSelf() {
System.out.println("I am an animal.");
}
}
// Dog 类
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println("Woof!");
}
public void introduceSelf() {
System.out.println("I am a dog named " + name + ".");
}
}
// Cat 类
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
public void meow() {
System.out.println("Meow!");
}
public void introduceSelf() {
System.out.println("I am a cat named " + name + ".");
}
}
// 测试程序
public class Test {
public static void main(String[] args) {
// 单个对象测试
Animal animal = new Animal("Animal");
animal.introduceSelf();
Dog dog = new Dog("Fido");
dog.introduceSelf();
dog.bark();
Cat cat = new Cat("Whiskers");
cat.introduceSelf();
cat.meow();
// 数组化测试
Animal[] animals = new Animal[3];
animals[0] = new Animal("Animal");
animals[1] = new Dog("Fido");
animals[2] = new Cat("Whiskers");
for (Animal a : animals) {
a.introduceSelf();
}
// 参数化测试
introduceAnimal(new Animal("Animal"));
introduceAnimal(new Dog("Fido"));
introduceAnimal(new Cat("Whiskers"));
}
public static void introduceAnimal(Animal animal) {
animal.introduceSelf();
}
}
```
运行结果:
```
I am an animal.
I am a dog named Fido.
Woof!
I am a cat named Whiskers.
Meow!
I am an animal.
I am a dog named Fido.
I am a cat named Whiskers.
I am an animal.
I am a dog named Fido.
I am a cat named Whiskers.
```
阅读全文