定义一个教师类(Teacher):该类提供教师的工号和姓名信息;再定义一个课程类(Course):该类描述了课程的编号和课程名称,每门课程都要指定一个教师。 要求:创建一个课程对象,通过该对象获得任课教师对象的信息并输出。
时间: 2024-10-12 22:08:33 浏览: 139
首先,我们定义一个`Teacher`类,用于存储教师的工号和姓名:
```java
public class Teacher {
private int teacherId;
private String name;
public Teacher(int id, String name) {
this.teacherId = id;
this.name = name;
}
// getter 和 setter 方法
public int getTeacherId() {
return teacherId;
}
public void setTeacherId(int teacherId) {
this.teacherId = teacherId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
接下来,定义`Course`类,它包含了课程编号、课程名称以及引用`Teacher`对象的属性:
```java
public class Course {
private int courseId;
private String courseName;
private Teacher teacher;
public Course(int id, String name, Teacher teacher) {
this.courseId = id;
this.courseName = name;
this.teacher = teacher;
}
// getter 和 setter 方法
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return "Course{" +
"courseId=" + courseId +
", courseName='" + courseName + '\'' +
", teacher=" + teacher.getName() +
'}';
}
}
```
现在我们可以创建一个具体的`Teacher`对象和`Course`对象,并通过`Course`对象获取教师信息:
```java
public static void main(String[] args) {
Teacher teacher = new Teacher(001, "张三");
Course course = new Course(001, "数学", teacher);
System.out.println("课程信息: " + course);
// 这将打印出: 课程信息: Course{courseId=001, courseName='数学', teacher=张三}
}
```
阅读全文