用java的方式创建父类:动物。拥有姓名、月份、物种三个属性;有吃东西、输出年龄的方法。" 创建子类狗 继承父类 有体重和屋巴两个属性:有定义屋巴形状、输出物种、获取体重的方法。" 创建子类企鹅,继承父类,有体重这个属性;有跑、输出物种、获取体重的方法。"创建测试类,定义企鹅、输出方法;定义狗,输出方法。
时间: 2023-12-10 19:42:00 浏览: 165
java_java课设_java课程设计_动物换位_
5星 · 资源好评率100%
下面是Java代码实现:
```java
//动物类
public class Animal {
private String name;
private int month;
private 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 getAge() {
System.out.println(name + " is " + month + " months old.");
}
public String getSpecies() {
return species;
}
}
//狗类
public class Dog extends Animal {
private double weight;
private String bark;
public Dog(String name, int month, String species, double weight, String bark) {
super(name, month, species);
this.weight = weight;
this.bark = bark;
}
public void setBark(String bark) {
this.bark = bark;
}
public void getWeight() {
System.out.println(getSpecies() + " " + getName() + "'s weight is " + weight + "kg.");
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setShape(String shape) {
System.out.println(getSpecies() + " " + getName() + "'s house shape is " + shape);
}
}
//企鹅类
public 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(getName() + " is running.");
}
public void getWeight() {
System.out.println(getSpecies() + " " + getName() + "'s weight is " + weight + "kg.");
}
public void setWeight(double weight) {
this.weight = weight;
}
}
//测试类
public class Test {
public static void main(String[] args) {
Dog dog = new Dog("Tom", 12, "Golden Retriever", 25.6, "Wang Wang");
dog.eat();
dog.getAge();
dog.getWeight();
dog.setShape("Round");
Penguin penguin = new Penguin("Jerry", 6, "Emperor Penguin", 10.3);
penguin.eat();
penguin.getAge();
penguin.getWeight();
penguin.run();
}
}
```
阅读全文