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

后端 未结 12 1733
傲寒
傲寒 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:51

    Maybe you do not need to add the course name to student. What I would do is add Students to some datastructure in Course. This is cleaner and reduces the coupling between Course and Student. This would also allow you to have Students being in more than one course. For example:

    public class Course extends Student{
        private Award courseAward;
        private String courseCode;
        public String courseTitle;
        private Student courseLeader;//change to a student Object
        private int courseDuration;
        private boolean courseSandwich;
        private Set students;//have course hold a collection of students
    
    /**
     * Constructor for objects of class Course
     */
    public Course(String code, String title, Award award, Student leader, int duration, boolean sandwich){
        courseCode = code;
        courseTitle = title;
        courseAward = award;
        courseLeader = leader;
        courseDuration = duration;
        courseSandwich = sandwich;
        this.students=new HashSet();
    }
    
    public boolean addStudent(Student student){
        return students.add(student);
    }
    
    public Set getStudents(){
        return students;
    } 
    

    }

提交回复
热议问题