用Java设计一个教材类,一个课程类,及一个为某门课程指定参考教材的类。一门课程可以有多本参考教材,再设计一个测试类。
时间: 2023-07-16 20:12:12 浏览: 109
教材类:
```java
public class Textbook {
private String name;
private String author;
public Textbook(String name, String author) {
this.name = name;
this.author = author;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
}
```
课程类:
```java
import java.util.ArrayList;
public class Course {
private String name;
private ArrayList<Textbook> textbooks;
public Course(String name) {
this.name = name;
textbooks = new ArrayList<>();
}
public void addTextbook(Textbook textbook) {
textbooks.add(textbook);
}
public ArrayList<Textbook> getTextbooks() {
return textbooks;
}
public String getName() {
return name;
}
}
```
为某门课程指定参考教材的类:
```java
public class CourseTextbook {
private Course course;
private Textbook textbook;
public CourseTextbook(Course course, Textbook textbook) {
this.course = course;
this.textbook = textbook;
}
public Course getCourse() {
return course;
}
public Textbook getTextbook() {
return textbook;
}
}
```
测试类:
```java
public class Test {
public static void main(String[] args) {
Textbook tb1 = new Textbook("Java编程思想", "Bruce Eckel");
Textbook tb2 = new Textbook("Effective Java", "Joshua Bloch");
Course course = new Course("Java编程");
course.addTextbook(tb1);
course.addTextbook(tb2);
CourseTextbook ct1 = new CourseTextbook(course, tb1);
CourseTextbook ct2 = new CourseTextbook(course, tb2);
System.out.println(ct1.getCourse().getName() + "的参考教材有:");
for (Textbook tb : ct1.getCourse().getTextbooks()) {
System.out.println(tb.getName() + " - " + tb.getAuthor());
}
System.out.println(ct2.getCourse().getName() + "的参考教材有:");
for (Textbook tb : ct2.getCourse().getTextbooks()) {
System.out.println(tb.getName() + " - " + tb.getAuthor());
}
}
}
```
输出:
```
Java编程的参考教材有:
Java编程思想 - Bruce Eckel
Effective Java - Joshua Bloch
Java编程的参考教材有:
Java编程思想 - Bruce Eckel
Effective Java - Joshua Bloch
```
阅读全文