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

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

    As mentioned, stay away from the "extends" for this. In general, you shouldn't use it unless the "is-a" relationship makes sense.

    You should probably provide getters for the methods on the Course class:

    public class Course {
       ...
       public String getTitle() {
           return title;
       }
    }
    

    And then if the Student class needs that, it would somehow get a hold of the course (which is up to you in your design), and call the getter:

    public class Student {
       private Set courses = new HashSet();
    
       public void attendCourse(Course course) {
           courses.add(course);
       }
    
       public void printCourses(PrintStream stream) {
           for (Course course : courses) {
               stream.println(course.getTitle());
           }
       }
    }
    

提交回复
热议问题