1.定义一个动物类包括品种,年龄,性别公共属性方法有eat(),sleep() 2.定义动物类的子类(Dog)除父类的属性和方法外,添加color()属性和shout()方法3.定义动物类的子类bird,除了父类的属性和方法外添加fly()方法
时间: 2024-11-27 07:16:04 浏览: 9
Zoo_java_动物园_zoo类网站_Zoo类_
为了实现您的需求,我们首先创建一个名为"Animal"的基类,它包含了物种、年龄和性别的属性以及基本的吃和睡方法:
```java
public class Animal {
private String species;
private int age;
private String gender;
public Animal(String species, int age, String gender) {
this.species = species;
this.age = age;
this.gender = gender;
}
public abstract void eat();
public abstract void sleep();
// 其他访问和设置方法...
}
```
接着,我们为Dog类和Bird类分别扩展Animal类:
```java
public class Dog extends Animal {
private String color;
public Dog(String species, int age, String gender, String color) {
super(species, age, gender);
this.color = color;
}
@Override
public void eat() {
System.out.println("Dog is eating.");
}
public void shout() {
System.out.println("Dog is shouting.");
}
// 特有的属性和方法
public String getColor() { return color; }
}
public class Bird extends Animal {
private boolean canFly;
public Bird(String species, int age, String gender) {
super(species, age, gender);
this.canFly = true;
}
@Override
public void eat() {
System.out.println("Bird is eating.");
}
public void fly() {
if (canFly) {
System.out.println("Bird is flying.");
} else {
System.out.println("This bird cannot fly.");
}
}
// 特有的属性和方法
public boolean isFlying() { return canFly; }
}
```
现在,Dog类有一个颜色属性和喊叫的方法,Bird类则有自己的飞行能力属性和飞翔的方法。
阅读全文