用java定义person类和student类,分别实现定义各自基本属性的功能
时间: 2024-05-08 19:21:13 浏览: 134
下面是Java定义Person类和Student类的示例代码:
```java
// Person类定义
public class Person {
// 基本属性
private String name;
private int age;
private String gender;
// 构造函数
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
// Student类定义,继承自Person类
public class Student extends Person {
// 基本属性
private String school;
private String major;
// 构造函数
public Student(String name, int age, String gender, String school, String major) {
super(name, age, gender);
this.school = school;
this.major = major;
}
// getter和setter方法
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
```
在上面的代码中,Person类定义了基本属性name、age和gender,并提供了构造函数和getter/setter方法来实现对这些属性的设置和获取。
Student类继承自Person类,除了继承了Person类的基本属性外,还定义了自己的基本属性school和major,并同样提供了构造函数和getter/setter方法来实现对这些属性的设置和获取。
阅读全文