实现猫和老虎类,猫和老虎继承animal,同时写eat和run方法,设置扩展属性和方法
时间: 2024-10-09 14:08:49 浏览: 34
多重接口示例-C#继承PPT完整课件
在面向对象编程中,你可以创建一个`Animal`基类作为所有动物的通用模板,然后分别定义`Cat`和`Tiger`两个子类,它们继承自`Animal`,并覆盖或扩展必要的功能。
首先,我们创建一个`Animal`基类:
```java
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// 定义通用的行为
public void eat() {
System.out.println(name + " is eating.");
}
public void run() {
System.out.println(name + " is running at a moderate speed.");
}
// 扩展属性和方法
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
```
接着,我们为`Cat`和`Tiger`这两个子类添加特定行为:
```java
public class Cat extends Animal {
public Cat(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println(name + " is eating fish.");
}
// 猫的特有方法
public void climbTree() {
System.out.println(name + " is climbing a tree.");
}
}
public class Tiger extends Animal {
public Tiger(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println(name + " is hunting and eating meat.");
}
// 老虎的特有方法
public void roar() {
System.out.println(name + " is roaring loudly.");
}
}
```
现在,你可以实例化`Cat`和`Tiger`对象,并通过它们的父类`Animal`引用调用方法,或者直接调用它们特有的方法:
```java
public static void main(String[] args) {
Cat cat = new Cat("Mimi", 3);
cat.eat(); // 输出: Mimi is eating fish.
cat.run();
cat.climbTree();
Tiger tiger = new Tiger("Leo", 5);
tiger.eat(); // 输出: Leo is hunting and eating meat.
tiger.run();
tiger.roar();
}
```
阅读全文