Mal*_*arp 7 java variables class call
我只是在做一些事情作为考试的练习,但是有一点我无法理解,就是使用属于一个类的变量,在另一个类中.
我有一个Course课程和一个Student课程.课程存储所有不同的课程,我只想要能够做的是在课堂学生中使用课程的名称.
这是我的课程课程:
public class Course extends Student
{
// instance variables - replace the example below with your own
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
/**
* Constructor for objects of class Course
*/
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
}
Run Code Online (Sandbox Code Playgroud)
这是学生:
public class Student
{
// instance variables - replace the example below with your own
private int studentNumber;
private String studentName;
private int studentPhone;
private String studentCourse;
/**
* Constructor for objects of class Student
*/
public Student(int number, String name, int phone)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = courseTitle;
}
}
Run Code Online (Sandbox Code Playgroud)
我在课程中使用' extends ' 是否正确?或者这是不必要的?
在我的学生构造函数中,我试图将类课程中的'courseTitle'分配给变量'studentCourse'.但我根本想不通怎么做!
提前感谢您的帮助,我期待着您的回复!
谢谢!
GET*_*Tah 11
我在课程中使用'extends'是否正确?或者这是不必要的?
不幸的是,如果您想知道您的继承是否正确,请使用is-a替换extends.一门课程是学生吗?答案是不.这意味着你不应该延长CourseStudent
学生可以参加Course,因此该Student课程可以有一个类型的成员变量Course.如果您的模型指定(学生可以参加多个课程),您可以定义课程列表.
这是一个示例代码:
public class Student{
//....
private Course course;
//...
public void attendCourse(Course course){
this.course = course;
}
public Course getCourse(){
return course;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以拥有以下内容:
Student bob = new Student(...);
Course course = new Course(...);
bob.attendCourse(course);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52387 次 |
| 最近记录: |