定义一个描述动物的抽象类Animal,包含:①实例变量有名字、年龄和雌雄;②一个构造器用来初始化以上变量;③一个抽象的方法voice来描述动物叫声的行为。定义Animal的几种子类,比如Cat、Dog、Tiger,实现方法shout打印:名字+叫声 测试几种子类,调用shout方法
时间: 2024-02-01 11:16:38 浏览: 169
下面是代码实现:
```java
abstract class Animal {
String name;
int age;
boolean isMale;
public Animal(String name, int age, boolean isMale) {
this.name = name;
this.age = age;
this.isMale = isMale;
}
public abstract void voice();
}
class Cat extends Animal {
public Cat(String name, int age, boolean isMale) {
super(name, age, isMale);
}
@Override
public void voice() {
System.out.println(name + " meows");
}
public void scratch() {
System.out.println(name + " scratches");
}
}
class Dog extends Animal {
public Dog(String name, int age, boolean isMale) {
super(name, age, isMale);
}
@Override
public void voice() {
System.out.println(name + " barks");
}
public void wagTail() {
System.out.println(name + " wags tail");
}
}
class Tiger extends Animal {
public Tiger(String name, int age, boolean isMale) {
super(name, age, isMale);
}
@Override
public void voice() {
System.out.println(name + " roars");
}
public void hunt() {
System.out.println(name + " hunts");
}
}
```
测试代码如下:
```java
public class Main {
public static void main(String[] args) {
Cat cat = new Cat("Tom", 3, true);
Dog dog = new Dog("Snoopy", 5, false);
Tiger tiger = new Tiger("Tony", 7, true);
cat.voice();
dog.voice();
tiger.voice();
}
}
```
输出:
```
Tom meows
Snoopy barks
Tony roars
```
阅读全文