java person类_定义一个Person类,含姓名、性别、年龄等字段;继承Person类设计
时间: 2024-03-15 21:47:41 浏览: 166
一个Student类,含学号、专业、班级等字段。
以下是Java代码实现:
```
public class Person {
private String name;
private String gender;
private int age;
// 构造函数
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
// getter 和 setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Student extends Person {
private String studentId;
private String major;
private String className;
// 构造函数
public Student(String name, String gender, int age, String studentId, String major, String className) {
super(name, gender, age);
this.studentId = studentId;
this.major = major;
this.className = className;
}
// getter 和 setter 方法
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
```
这里,我们定义了一个Person类,它有三个属性:姓名(name)、性别(gender)和年龄(age)。然后,我们定义了一个Student类,继承自Person类,它有三个额外的属性:学号(studentId)、专业(major)和班级(className)。我们使用super()构造函数来调用父类构造函数,以初始化从父类继承的属性。
阅读全文