java设计一个教材类,一个课程类,及一个为某门课程指定参考教材的类。一门课程可以有多本参考教材,再设计一个测试类。
时间: 2024-05-07 09:22:03 浏览: 104
教材类:
```java
public class Textbook {
private String name;
private String author;
private String publisher;
private int year;
public Textbook(String name, String author, String publisher, int year) {
this.name = name;
this.author = author;
this.publisher = publisher;
this.year = year;
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
```
课程类:
```java
import java.util.ArrayList;
import java.util.List;
public class Course {
private String name;
private List<Textbook> textbooks;
public Course(String name) {
this.name = name;
textbooks = new ArrayList<>();
}
public void addTextbook(Textbook textbook) {
textbooks.add(textbook);
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Textbook> getTextbooks() {
return textbooks;
}
public void setTextbooks(List<Textbook> textbooks) {
this.textbooks = textbooks;
}
}
```
为某门课程指定参考教材的类:
```java
public class CourseTextbook {
private Course course;
private Textbook textbook;
public CourseTextbook(Course course, Textbook textbook) {
this.course = course;
this.textbook = textbook;
course.addTextbook(textbook);
}
// getter and setter methods
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Textbook getTextbook() {
return textbook;
}
public void setTextbook(Textbook textbook) {
this.textbook = textbook;
}
}
```
测试类:
```java
public class Test {
public static void main(String[] args) {
// create textbooks
Textbook textbook1 = new Textbook("Java Programming", "John Smith", "ABC Publisher", 2020);
Textbook textbook2 = new Textbook("Python Programming", "Emily Lee", "XYZ Publisher", 2019);
// create courses
Course course1 = new Course("Java Programming");
Course course2 = new Course("Python Programming");
// assign textbooks to courses
CourseTextbook ct1 = new CourseTextbook(course1, textbook1);
CourseTextbook ct2 = new CourseTextbook(course2, textbook2);
// print out course information and its textbooks
System.out.println("Course: " + course1.getName());
for (Textbook t : course1.getTextbooks()) {
System.out.println("Textbook: " + t.getName() + " by " + t.getAuthor());
}
System.out.println("Course: " + course2.getName());
for (Textbook t : course2.getTextbooks()) {
System.out.println("Textbook: " + t.getName() + " by " + t.getAuthor());
}
}
}
```
阅读全文