用Java编写设计一个教材类,一个课程类,及一个为某门课程指定参考教材的类。一门课程可以有多本参考教材,再设计一个测试类。
时间: 2024-03-10 15:51:06 浏览: 156
好的,以下是一个简单的教材类、课程类、为某门课程指定参考教材的类以及测试类的Java代码:
教材类 `Textbook.java`:
```java
public class Textbook {
private String title;
private String author;
private int yearPublished;
public Textbook(String title, String author, int yearPublished) {
this.title = title;
this.author = author;
this.yearPublished = yearPublished;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getYearPublished() {
return yearPublished;
}
}
```
课程类 `Course.java`:
```java
import java.util.ArrayList;
public class Course {
private String name;
private int credit;
private ArrayList<Textbook> textbooks;
public Course(String name, int credit) {
this.name = name;
this.credit = credit;
this.textbooks = new ArrayList<>();
}
public String getName() {
return name;
}
public int getCredit() {
return credit;
}
public void addTextbook(Textbook textbook) {
textbooks.add(textbook);
}
public ArrayList<Textbook> getTextbooks() {
return textbooks;
}
}
```
为某门课程指定参考教材的类 `CourseTextbook.java`:
```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;
}
}
```
测试类 `Test.java`:
```java
public class Test {
public static void main(String[] args) {
// 创建教材
Textbook textbook1 = new Textbook("Java编程思想", "Bruce Eckel", 2000);
Textbook textbook2 = new Textbook("Effective Java", "Joshua Bloch", 2008);
// 创建课程
Course course1 = new Course("Java程序设计", 4);
Course course2 = new Course("高级Java程序设计", 3);
// 为课程1指定参考教材
CourseTextbook course1Textbook1 = new CourseTextbook(course1, textbook1);
CourseTextbook course1Textbook2 = new CourseTextbook(course1, textbook2);
course1.addTextbook(textbook1);
course1.addTextbook(textbook2);
// 输出课程1的信息及参考教材
System.out.println("课程名称:" + course1.getName());
System.out.println("学分:" + course1.getCredit());
System.out.println("参考教材:");
for (Textbook textbook : course1.getTextbooks()) {
System.out.println(textbook.getTitle() + "(" + textbook.getAuthor() + "," + textbook.getYearPublished() + ")");
}
// 为课程2指定参考教材
CourseTextbook course2Textbook1 = new CourseTextbook(course2, textbook2);
course2.addTextbook(textbook2);
// 输出课程2的信息及参考教材
System.out.println("课程名称:" + course2.getName());
System.out.println("学分:" + course2.getCredit());
System.out.println("参考教材:");
for (Textbook textbook : course2.getTextbooks()) {
System.out.println(textbook.getTitle() + "(" + textbook.getAuthor() + "," + textbook.getYearPublished() + ")");
}
}
}
```
在测试类中,我们创建了两个教材、两门课程以及为这两门课程指定了参考教材,并输出了课程信息以及参考教材信息。
阅读全文