定义一个抽象类AbsAnimal,要求如下 (1)包括属性name,weight,color; (2)定义其有参构造方法; (3)定义受保护的run方法,功能是打印输出"Animal run fastly"; (4)在main方法里实例化抽象对象a AbsAnimal a = new AbsAnimal(….) ,想一想为什么会报错?如果报错注释掉该语句。
时间: 2023-12-10 20:37:23 浏览: 83
Java面向对象(高级)- 抽象类与抽象方法(或abstract关键字)
以下是AbsAnimal抽象类的定义:
```java
public abstract class AbsAnimal {
protected String name;
protected double weight;
protected String color;
public AbsAnimal(String name, double weight, String color) {
this.name = name;
this.weight = weight;
this.color = color;
}
protected void run() {
System.out.println("Animal run fastly");
}
}
```
在main方法里实例化抽象对象a会报错,因为抽象类不能被实例化。正确的做法是定义一个子类继承AbsAnimal抽象类,并实例化子类对象:
```java
public class Dog extends AbsAnimal {
public Dog(String name, double weight, String color) {
super(name, weight, color);
}
public void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("旺财", 10.5, "黄色");
dog.run();
dog.bark();
}
}
```
输出结果为:
```
Animal run fastly
Dog barks
```
阅读全文