2.定义一个Anima1类,要求如下:4(1)息条cneduahtcmbeant (2)包括成员变量:名称name,体重weight,颜色color+ (3)包括动态方法run()(输出“run fastly”);eat()(输出“I love bone”) ←(4)定义重载方法run(String name),输出谁跑得快+ (5)包括有参构造方法(利用Eclipse的Generate Constructor using Fileds方法)+ (6)在main方法里新建一个对象a(new调用构造方法),然后打印输出a的成员变量,再调用run和eat方法 再定义一个Dog类,要求如下+ (7)继承父类Anima1,增加新的成员变量:种类category+(8)定义有参构造方法+ (9)重复父类的run()方法(输出“dog run fastly”);eat () (输出“dog love bone”) + (10)在main方法里新建一个对象dl(new调用构造方法,Dog d1 =new….),然后打印输出dl的run和 eat方法+
时间: 2024-02-09 20:11:42 浏览: 119
下面是Anima1类和Dog类的实现代码:
```
public class Anima1 {
private String name;
private double weight;
private String color;
// 有参构造方法
public Anima1(String name, double weight, String color) {
this.name = name;
this.weight = weight;
this.color = color;
}
// run方法
public void run() {
System.out.println("run fastly");
}
// eat方法
public void eat() {
System.out.println("I love bone");
}
// 重载run方法
public void run(String name) {
System.out.println(name + " runs fastly");
}
}
public class Dog extends Anima1 {
private String category;
// 有参构造方法
public Dog(String name, double weight, String color, String category) {
super(name, weight, color);
this.category = category;
}
// 继承并重写run方法
@Override
public void run() {
System.out.println("dog run fastly");
}
// 继承并重写eat方法
@Override
public void eat() {
System.out.println("dog love bone");
}
}
public class Main {
public static void main(String[] args) {
// 新建Anima1对象并调用方法
Anima1 a = new Anima1("Tom", 10.5, "white");
System.out.println("Name: " + a.name);
System.out.println("Weight: " + a.weight);
System.out.println("Color: " + a.color);
a.run();
a.eat();
a.run("Tom");
// 新建Dog对象并调用方法
Dog d1 = new Dog("Max", 12.3, "black", "Golden Retriever");
System.out.println("Category: " + d1.category);
d1.run();
d1.eat();
}
}
```
输出结果为:
```
Name: Tom
Weight: 10.5
Color: white
run fastly
I love bone
Tom runs fastly
Category: Golden Retriever
dog run fastly
dog love bone
```
阅读全文