写一个课程类: 包括属性:课程名;学时;任课老师; 提供无参的构造方法和一个有参的构造方法 使用有参构造方法创建五个对象:“c语言”,“Java编程”,“php网络编程”,“c++”,“数据结构”
时间: 2024-12-17 17:55:28 浏览: 8
在Java中,我们可以创建一个名为`Course`的类来表示课程,它包含课程名、学时和任课老师等属性。以下是这个类的简单实现:
```java
public class Course {
private String courseName;
private int creditHours;
private String teacher;
// 无参构造方法
public Course() {
this.courseName = "";
this.creditHours = 0;
this.teacher = "";
}
// 有参构造方法
public Course(String courseName, int creditHours, String teacher) {
this.courseName = courseName;
this.creditHours = creditHours;
this.teacher = teacher;
}
// 提供getter和setter方法
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public int getCreditHours() {
return creditHours;
}
public void setCreditHours(int creditHours) {
this.creditHours = creditHours;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return "Course{" +
"courseName='" + courseName + '\'' +
", creditHours=" + creditHours +
", teacher='" + teacher + '\'' +
'}';
}
public static void main(String[] args) {
// 创建五个课程对象
Course cLanguage = new Course("C语言", 4, "张三");
Course javaProgramming = new Course("Java编程", 6, "李四");
Course phpNetworking = new Course("PHP网络编程", 5, "王五");
Course cPlusPlus = new Course("C++", 7, "赵六");
Course dataStructures = new Course("数据结构", 8, "钱七");
// 打印每个课程信息
System.out.println(cLanguage);
System.out.println(javaProgramming);
System.out.println(phpNetworking);
System.out.println(cPlusPlus);
System.out.println(dataStructures);
}
}
```
在这个例子中,我们定义了一个`Course`类,并提供了两个构造方法,以及基本的属性访问方法。在`main`函数中,我们通过有参构造方法创建了五个`Course`对象并打印它们的信息。
阅读全文