创建父类Person属性有姓名年龄方法有两个构造方法,1个普通方法用于显示姓名和年龄,还有针对属性的输入输出方法创建子类Student属性有学号方法有两个构造方法;1个普通方法用于显示学号,姓名,年龄;创建测试类StudentTest进行测试。的代码
时间: 2024-05-08 21:17:56 浏览: 14
下面是一个示例代码:
```java
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
this("", 0);
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
class Student extends Person {
private String id;
public Student(String name, int age, String id) {
super(name, age);
this.id = id;
}
public Student(String id) {
super();
this.id = id;
}
public void display() {
System.out.println("ID: " + id + ", Name: " + getName() + ", Age: " + getAge());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public class StudentTest {
public static void main(String[] args) {
Student student1 = new Student("001", "John", 20);
Student student2 = new Student("002");
student2.setName("Mary");
student2.setAge(19);
student1.display();
student2.display();
}
}
```
如果您有任何问题,请随时问我哦!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)