我只是通过一些练习来练习我正在练习的练习题,但有一件事我无法理解,就是在一个不同的班级中使用属于一个班级的变量。如何在Java的另一个类中使用一个类的变量?
我有课程课程和学生课程。班级课程存储所有不同的课程,我只想在班级学生中使用该课程的名称。
这是我的课程类:
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;
}
}
这里是学生:
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;
}
}
我是在利用场内 '延伸' 正确吗?或者这是不必要的?
在我的学生构造函数中,我试图将课程'courseTitle'分配给变量'studentCourse'。但我根本无法想象如何做到这一点!
非常感谢您的帮助,我期待您的回音!
谢谢!
我不认为你需要这种情况下的多对多连接表(登记对象)的额外层。 (除非这需要在传统数据库中保留) –
@John:是的,但是由于OP显然已经暴露于某些滥用面向对象的可怕示例,所以我宁愿展示一个更为彻底的模型替代方案。 –
这是有道理的。 –