Java定义一个Person类,含:姓名、性别、年龄等字段;继承Person类设计Teacher类,增加:职称、部门等字段;继承Person类设计Student类,增加:学号、班级等字段。定义各类的构造方法和toString0方法,并分别创建对象进行测试。
时间: 2023-06-06 16:08:45 浏览: 195
关于java中的类
这是一个关于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;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
public String toString() {
return "Name: " + name + "\n" +
"Gender: " + gender + "\n" +
"Age: " + age + "\n";
}
}
public class Teacher extends Person {
private String title;
private String department;
public Teacher(String name, String gender, int age, String title, String department) {
super(name, gender, age);
this.title = title;
this.department = department;
}
public String getTitle() {
return title;
}
public String getDepartment() {
return department;
}
public String toString() {
return super.toString() +
"Title: " + title + "\n" +
"Department: " + department + "\n";
}
}
public class Student extends Person {
private int studentId;
private String className;
public Student(String name, String gender, int age, int studentId, String className) {
super(name, gender, age);
this.studentId = studentId;
this.className = className;
}
public int getStudentId() {
return studentId;
}
public String getClassName() {
return className;
}
public String toString() {
return super.toString() +
"Student ID: " + studentId + "\n" +
"Class Name: " + className + "\n";
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
Person person = new Person("Tom", "Male", 20);
Teacher teacher = new Teacher("John", "Male", 30, "Professor", "Computer Science");
Student student = new Student("Lily", "Female", 18, 1001, "Class A");
System.out.println(person.toString());
System.out.println(teacher.toString());
System.out.println(student.toString());
}
}
```
运行以上代码,输出如下:
```
Name: Tom
Gender: Male
Age: 20
Name: John
Gender: Male
Age: 30
Title: Professor
Department: Computer Science
Name: Lily
Gender: Female
Age: 18
Student ID: 1001
Class Name: Class A
```
阅读全文