定义Human类 属性:姓名,年龄; 方法:走路。 定义Human类的子类Child 新增属性:学校名; 构造方法:有参数,给Child的所有属性赋值; 新增方法:上学。 定义一个Demo类,在main方法中创建一个姓名为“小明”,年龄为9岁,在“红旗小学”上学的Child对象,调用对象的走路和上学方法。
时间: 2024-04-21 14:30:22 浏览: 18
好的,以下是Java代码实现:
```java
// 定义Human类
class Human {
String name; // 姓名
int age; // 年龄
// 走路方法
void walk() {
System.out.println(name + "正在走路");
}
}
// 定义Child类作为Human的子类
class Child extends Human {
String schoolName; // 学校名
// 有参数构造方法,初始化Child的所有属性
Child(String name, int age, String schoolName) {
this.name = name;
this.age = age;
this.schoolName = schoolName;
}
// 上学方法
void goToSchool() {
System.out.println(name + "正在去" + schoolName + "上学");
}
}
// 定义Demo类
class Demo {
public static void main(String[] args) {
// 创建一个Child对象
Child xiaoming = new Child("小明", 9, "红旗小学");
// 调用对象的走路和上学方法
xiaoming.walk();
xiaoming.goToSchool();
}
}
```
输出结果为:
```
小明正在走路
小明正在去红旗小学上学
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)