利用Java代码定义一个person类,包含姓名、性别、年龄等字段;继承person类,设计teacher类,增加:职称、部门等字段;继承person类设计Student类增加,学号、班级等字段,定义各类的构造方法和to String()方法,并分贝创建对象进行测试
时间: 2023-06-07 20:08:27 浏览: 102
好的,请稍等。以下是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 toString() {
return "Name: " + name + ", Gender: " + gender + ", Age: " + age;
}
}
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 toString() {
return super.toString() + ", Title: " + title + ", Department: " + department;
}
}
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;
}
public String toString() {
return super.toString() + ", Student ID: " + studentID + ", Class Name: " + className;
}
}
// 测试代码
public static void main(String[] args) {
Person person = new Person("Alice", "Female", 25);
System.out.println(person);
Teacher teacher = new Teacher("Bob", "Male", 35, "Professor", "Computer Science");
System.out.println(teacher);
Student student = new Student("Charlie", "Male", 18, "123456", "Class A");
System.out.println(student);
}
```
这个代码定义了一个Person类,然后分别继承了这个类来设计Teacher和Student类。每个类都有自己的构造方法和toString()方法,用于创建对象和输出对象属性。在测试代码中,我们创建了一个Person对象,一个Teacher对象和一个Student对象,并将它们的属性打印到控制台上。
阅读全文