3.定义一个抽象类AbsAnimal,要求如下。 (1)包括属性name, weight, color; (2)定义具有参构造方法; (3)定义受保护的run方法,功能是打印输出"Animal run fastly"; (4)在main方法里实例化抽象对象a AbsAnimal a = new AbsAnimall(...),想想为什 么会报错?如果报错注释掉该语句。
时间: 2024-02-27 18:53:06 浏览: 26
以下是定义一个抽象类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");
}
public static void main(String[] args) {
// 这里会报错,因为抽象类无法被实例化
// AbsAnimal a = new AbsAnimal("dog", 10.5, "white");
}
}
```
在该抽象类中,定义了三个属性:name、weight、color,分别表示动物的名字、体重和颜色。同时定义了一个具有参构造方法,用于初始化这三个属性。另外,还定义了一个受保护的run方法,用于打印输出"Animal run fastly"。需要注意的是,这里的run方法是受保护的,只能在子类中访问。
在main方法中,我们尝试实例化一个抽象对象a,但是会报错,因为抽象类无法被实例化。如果想要使用该类,需要定义一个子类并实现其中的抽象方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)