1.定义Human类 属性:姓名,年龄; 方法:走路。 定义Human类的子类Child 新增属性:学校名; 构造方法:有参数,给Child的所有属性赋值; 新增方法:上学。 定义一个Demo类,在main方法中创建一个姓名为“小明”,年龄为9岁,在“红旗小学”上学的Child对象,调用对象的走路和上学方法。
时间: 2024-03-15 08:43:11 浏览: 32
好的,这是一个基于Java语言的面向对象编程问题,下面是代码实现:
```
// Human类
class Human {
String name;
int age;
public void walk() {
System.out.println(name + "正在走路");
}
}
// Child类
class Child extends Human {
String schoolName;
public Child(String name, int age, String schoolName) {
this.name = name;
this.age = age;
this.schoolName = schoolName;
}
public void goSchool() {
System.out.println(name + "正在去" + schoolName + "上学");
}
}
// Demo类
public class Demo {
public static void main(String[] args) {
Child child = new Child("小明", 9, "红旗小学");
child.walk();
child.goSchool();
}
}
```
在以上代码中,我们首先定义了一个`Human`类,包含了姓名和年龄两个属性和一个走路的方法。然后我们定义了`Child`类,它继承了`Human`类,并且新增了学校名这个属性和上学这个方法。最后我们在`Demo`类中创建了一个`Child`对象,调用了它的走路和上学方法,输出了相关信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)