I'm just working through a few things as practice for an exam I have coming up, but one thing I cannot get my head round, is using a variable that belongs to one class, in a different class.
I have a Course class and a Student class. Class course stores all the different courses and what I simply want to be able to do is use the name of the course, in class Student.
Here is my Course class:
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;
}
}
And here is Student:
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;
}
}
Am I correct in using 'extends' within Course? Or is this unnecessary?
In my constructor for Student, I am trying to assign 'courseTitle' from class Course, to the variable 'studentCourse'. But I simply cannot figure how to do this!
Thank you in advance for your help, I look forward to hearing from you!
Thanks!
解决方案
Am I correct in using 'extends' within Course? Or is this unnecessary?
Unfortunately not, if you want to know whether your inheritance is correct or not, replace extends with is-a. A course is a student? The answer is no. Which means your Course should not extend Student
A student can attend a Course, hence the Student class can have a member variable of type Course. You can define a list of courses if your model specifies that (a student can attend several courses).
Here is a sample code:
public class Student{
//....
private Course course;
//...
public void attendCourse(Course course){
this.course = course;
}
public Course getCourse(){
return course;
}
}
Now, you can have the following:
Student bob = new Student(...);
Course course = new Course(...);
bob.attendCourse(course);