使用java生成设计一个教材类,一个课程类,及一个为某门课程指定参考教材的类。一门课程可以有多本参考教材,再设计一个测试类。
时间: 2023-05-29 10:04:59 浏览: 192
教材类:
```java
public class Textbook {
private String title;
private String author;
private String publisher;
private int year;
public Textbook(String title, String author, String publisher, int year) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.year = year;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public int getYear() {
return year;
}
}
```
课程类:
```java
import java.util.ArrayList;
public class Course {
private String name;
private ArrayList<Textbook> textbooks;
public Course(String name) {
this.name = name;
this.textbooks = new ArrayList<>();
}
public String getName() {
return name;
}
public void addTextbook(Textbook textbook) {
textbooks.add(textbook);
}
public ArrayList<Textbook> getTextbooks() {
return 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);
}
public Course getCourse() {
return course;
}
public Textbook getTextbook() {
return textbook;
}
}
```
测试类:
```java
public class Test {
public static void main(String[] args) {
Course course = new Course("Java Programming");
Textbook textbook1 = new Textbook("Java: A Beginner's Guide", "Herbert Schildt", "McGraw-Hill", 2018);
Textbook textbook2 = new Textbook("Head First Java", "Kathy Sierra and Bert Bates", "O'Reilly Media", 2005);
CourseTextbook courseTextbook1 = new CourseTextbook(course, textbook1);
CourseTextbook courseTextbook2 = new CourseTextbook(course, textbook2);
System.out.println("Course: " + course.getName());
System.out.println("Textbooks:");
for (Textbook textbook : course.getTextbooks()) {
System.out.println(textbook.getTitle() + ", " + textbook.getAuthor() + ", " +
textbook.getPublisher() + ", " + textbook.getYear());
}
}
}
```
输出:
```
Course: Java Programming
Textbooks:
Java: A Beginner's Guide, Herbert Schildt, McGraw-Hill, 2018
Head First Java, Kathy Sierra and Bert Bates, O'Reilly Media, 2005
```
阅读全文