利用Java的代码定义一个person类,包含姓名、性别、年龄等字段;继承person类,设计teacher类,增加:职称、部门等字段;继承person类设计Student类增加,学号、班级等字段,定义各类的构造方法和to String()方法,并分贝创建对象进行测试
时间: 2023-06-06 07:07:03 浏览: 130
Java类继承代码示例,定义Person类,Student类继承自Person类,并添加其他信息
好的,这是一个关于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;
}
@Override
public String toString() {
return "Person{" +
"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;
}
@Override
public String toString() {
return "Teacher{" +
"name='" + super.getName() + '\'' +
", gender='" + super.getGender() + '\'' +
", age=" + super.getAge() +
", 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;
}
@Override
public String toString() {
return "Student{" +
"name='" + super.getName() + '\'' +
", gender='" + super.getGender() + '\'' +
", age=" + super.getAge() +
", studentID='" + studentID + '\'' +
", className='" + className + '\'' +
'}';
}
}
// 在主函数中进行对象的测试
public class Main {
public static void main(String[] args) {
Person person = new Person("小明", "男", 18);
System.out.println(person);
Teacher teacher = new Teacher("张老师", "女", 30, "高级教师", "物理系");
System.out.println(teacher);
Student student = new Student("小红", "女", 16, "S001", "高一1班");
System.out.println(student);
}
}
```
以上代码就是一个简单的实现,你可以根据需要进行修改。
阅读全文