创建父类:动物。拥有姓名、月份、物种三个属性,有吃东西、输出年龄的方法。 创建子类狗,继承父类,有体重和尾巴两个属性,有定义尾巴形状、输出物种、获取体重的方法。 创建子类企鹅,继承父类,有体重这个属性,有跑、输出物种、获取体重的方法。 创建测试类。定义企鹅、输出方法,定义狗,输出方法。 用Java写
时间: 2024-02-05 15:13:21 浏览: 58
以下是Java代码实现:
```java
// 父类 Animal
class Animal {
protected String name;
protected int month;
protected String species;
public Animal(String name, int month, String species) {
this.name = name;
this.month = month;
this.species = species;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void outputAge() {
System.out.println(name + " is " + month + " months old.");
}
}
// 子类 Dog
class Dog extends Animal {
private double weight;
private String tailShape;
public Dog(String name, int month, String species, double weight, String tailShape) {
super(name, month, species);
this.weight = weight;
this.tailShape = tailShape;
}
public void defineTailShape(String shape) {
tailShape = shape;
System.out.println(name + "'s tail shape is " + tailShape + ".");
}
public void outputSpecies() {
System.out.println(name + " is a " + species + ".");
}
public double getWeight() {
return weight;
}
}
// 子类 Penguin
class Penguin extends Animal {
private double weight;
public Penguin(String name, int month, String species, double weight) {
super(name, month, species);
this.weight = weight;
}
public void run() {
System.out.println(name + " is running.");
}
public void outputSpecies() {
System.out.println(name + " is a " + species + ".");
}
public double getWeight() {
return weight;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
// 创建企鹅对象
Penguin penguin = new Penguin("Peng", 6, "Emperor penguin", 20.5);
// 输出物种和体重
penguin.outputSpecies();
System.out.println(penguin.getWeight());
// 创建狗对象
Dog dog = new Dog("Max", 12, "Golden retriever", 25.8, "curled");
// 输出物种和体重
dog.outputSpecies();
System.out.println(dog.getWeight());
}
}
```
阅读全文