How to use a variable of one class, in another in Java?

后端 未结 12 1755
傲寒
傲寒 2021-01-18 02:00

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

12条回答
  •  长发绾君心
    2021-01-18 02:43

    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);
    

提交回复
热议问题