1、设计一个动物类(Aniaml): 成员方法:吃(eat)、睡觉(sleep)、移动(move)。 2、设计一个兔子类(Rabbit)继承动物类,重写父类的eat方法; 3、设计一个狮子类(Tiger)继承动物类,重写父类的eat方法; 4、在主类中,分别生成兔子对象r,狮子对象t,输出r和t的吃、睡觉和 移动的行为。
时间: 2024-01-05 20:05:17 浏览: 143
java类的设计举例-animal
下面是代码实现:
```java
// Animal类
class Animal {
public void eat() {
System.out.println("Animal is eating...");
}
public void sleep() {
System.out.println("Animal is sleeping...");
}
public void move() {
System.out.println("Animal is moving...");
}
}
// Rabbit类
class Rabbit extends Animal {
@Override
public void eat() {
System.out.println("Rabbit is eating grass...");
}
}
// Tiger类
class Tiger extends Animal {
@Override
public void eat() {
System.out.println("Tiger is eating meat...");
}
}
// 主类
public class Main {
public static void main(String[] args) {
Rabbit r = new Rabbit();
r.eat();
r.sleep();
r.move();
Tiger t = new Tiger();
t.eat();
t.sleep();
t.move();
}
}
```
输出结果如下:
```
Rabbit is eating grass...
Animal is sleeping...
Animal is moving...
Tiger is eating meat...
Animal is sleeping...
Animal is moving...
```
阅读全文