java定义一个Animal类要求如下: (1)包括成员变量:名称name,体重weight,颜色color (2)包括动态方法run()(输出“run fastly”);eat()(输出“I love bone”) (3)定义重载方法run(String name),输出谁跑得快 (4)包括有参构造方法(利用Eclipse的Generate Constructor using Fileds方法) (5)在main方法里新建一个对象a(new调用构造方法),然后打印输出a的成员变量,再调用run和eat方法再定义一个Dog类,要求如下 (6)继承父类Animal,增加新的成员变量:种类category (7)定义有参构造方法 (8)重写父类的run()方法(输出“dog run fastly”);eat()(输出“dog love bone”) (9)在main方法里新建一个对象d1(new调用构造方法,Dog d1 = new ….),然后打印输出d1的run和eat方法
时间: 2023-07-16 18:13:50 浏览: 113
以下是Java定义Animal类和Dog类的代码:
Animal类:
```
public class Animal {
private String name;
private double weight;
private String color;
public Animal(String name, double weight, String color) {
this.name = name;
this.weight = weight;
this.color = color;
}
public void run() {
System.out.println("run fastly");
}
public void eat() {
System.out.println("I love bone");
}
public void run(String name) {
System.out.println(name + " runs fastly");
}
public String getName() {
return name;
}
public double getWeight() {
return weight;
}
public String getColor() {
return color;
}
}
```
Dog类:
```
public class Dog extends Animal {
private String category;
public Dog(String name, double weight, String color, String category) {
super(name, weight, color);
this.category = category;
}
@Override
public void run() {
System.out.println("dog run fastly");
}
@Override
public void eat() {
System.out.println("dog love bone");
}
public String getCategory() {
return category;
}
}
```
在main方法里新建一个Animal对象和一个Dog对象,并输出它们的成员变量、调用它们的run和eat方法:
```
public static void main(String[] args) {
Animal a = new Animal("Animal1", 10.0, "brown");
System.out.println("Animal name: " + a.getName());
System.out.println("Animal weight: " + a.getWeight());
System.out.println("Animal color: " + a.getColor());
a.run();
a.eat();
a.run("Animal1");
Dog d1 = new Dog("Dog1", 8.0, "black", "Golden Retriever");
System.out.println("Dog name: " + d1.getName());
System.out.println("Dog weight: " + d1.getWeight());
System.out.println("Dog color: " + d1.getColor());
System.out.println("Dog category: " + d1.getCategory());
d1.run();
d1.eat();
}
```
输出结果:
```
Animal name: Animal1
Animal weight: 10.0
Animal color: brown
run fastly
I love bone
Animal1 runs fastly
Dog name: Dog1
Dog weight: 8.0
Dog color: black
Dog category: Golden Retriever
dog run fastly
dog love bone
```
阅读全文