用Java代码定义一个person类,包含姓名、性别、年龄等字段;继承person类,设计teacher类,增加:职称、部门等字段;继承person类设计Student类增加,学号、班级等字段,定义各类的构造方法和toString()方法,并分贝创建对象进行测试
时间: 2023-06-08 18:04:44 浏览: 603
关于java中的类
好的,开始回答。
以下是Java代码实现:
```
// Person类
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
}
}
// Teacher类
public class Teacher extends Person {
private String jobTitle;
private String department;
public Teacher(String name, String gender, int age, String jobTitle, String department) {
super(name, gender, age);
this.jobTitle = jobTitle;
this.department = department;
}
// getter和setter方法
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Teacher{" +
"jobTitle='" + jobTitle + '\'' +
", department='" + department + '\'' +
"} " + super.toString();
}
}
// Student类
public class Student extends Person {
private String studentId;
private String className;
public Student(String name, String gender, int age, String studentId, String className) {
super(name, gender, age);
this.studentId = studentId;
this.className = className;
}
// getter和setter方法
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public String toString() {
return "Student{" +
"studentId='" + studentId + '\'' +
", className='" + className + '\'' +
"} " + super.toString();
}
}
// 测试
public class Test {
public static void main(String[] args) {
Person person = new Person("张三", "男", 20);
System.out.println(person);
Teacher teacher = new Teacher("李四", "女", 30, "教授", "计算机系");
System.out.println(teacher);
Student student = new Student("王五", "男", 18, "001", "计算机科学与技术");
System.out.println(student);
}
}
```
以上代码实现了定义Person、Teacher和Student三个类,并且实现了各自的构造方法和toString()方法。同时,分别创建了person、teacher和student三个对象,并且在main方法中对它们进行了输出测试。
阅读全文