简体   繁体   English

如何在Java中使用另一类的变量?

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

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. 课堂课程存储所有不同的课程,而我只是想做的就是使用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'. 在我的Student构造函数中,我试图将Course类中的“ courseTitle”分配给变量“ 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 . 不幸的是,如果您想知道您的继承是否正确,请使用is-a替换extends A course is a student? 一门课程是学生吗? The answer is no. 答案是不。 Which means your Course should not extend Student 这意味着您的Course不应扩展Student

A student can attend a Course , hence the Student class can have a member variable of type Course . 学生可以参加Course ,因此Student类可以具有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);

我认为课程不是学生,因此在这些课程之间进行继承可能不是一个好主意。

You have to declare them public. 您必须宣布它们为公开。

A better way is the keep them private, and code a public getter for that variable. 更好的方法是将它们设为私有,并为该变量编写公共获取程序。 for example: 例如:

public Award getCourseAward(){
         return this.courseAward;
}

Course should not extend Student . Course不应扩展Student If you want to access the courseTitle field of Course , you need to pass a reference to a Course object to the Student and then do course.CourseTitle. 如果要访问CoursecourseTitle字段,则需要courseTitle Course对象的引用传递给Student ,然后执行course.CourseTitle。

You cannot access private attributes of a class from another, this is one of the main principles of OOP: encapsulation. 您不能从另一个类访问一个类的私有属性,这是OOP的主要原则之一:封装。 You have to provide access method to those attribute, you want to publish outside the class. 您必须提供对那些属性的访问方法,并且要在类外部发布。 The common approach is setter/getters - getters only, if you want to have your class immutable. 通用的方法是setter / getters-仅当想要使类不可变时才使用getter。 Look here: http://en.wikipedia.org/wiki/Mutator_method#Java_example 在这里查看: http : //en.wikipedia.org/wiki/Mutator_method#Java_example

It does not make sense to arbitrarily extend classes. 任意扩展类是没有意义的。 Student is not a Course or vice versa, so you cannot extend them like that. 学生不是课程,反之亦然,因此您不能那样扩展它们。

What you need to do is: 您需要做的是:

create a Course first: 首先创建一个课程:

       Course aCourse = new Course(..);

create a Student: 创建学生:

       Student aStudent = new Student(..);

assign the Course to the Student: 将课程分配给学生:

       aStudent.setCourse(aCourse.title);

Extending Student with Couse because they are not of the same kind. Couse 扩展 Student ,因为它们不是同一类。 Extending one class with another happens when specializing a more general (in a sense) one. 当专门研究更一般的(某种意义上)的一门课时,就会发生将一门课与另一门课相结合的情况。
The solution would be to pass courseTitle as an argument of the Student constructor 解决方案是将courseTitle作为Student构造函数的参数传递

There should be 3 separate objects here, a Course, a Student, and an Enrollment. 这里应该有3个单独的对象,一个课程,一个学生和一个注册。 An enrollment connects a Student to a Course, a Course has many Students, and a Student can enroll in many courses. 一个注册将一个学生连接到一个课程,一个课程有许多学生,并且一个学生可以注册许多课程。 None of them should extend each other. 它们都不应该相互延伸。

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<Student> 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<Student>();
}

public boolean addStudent(Student student){
    return students.add(student);
}

public Set<Student> getStudents(){
    return students;
} 

} }

First, 第一,

You are extending Student class in Course class, which means, student class gets all the coruse class properties. 您要在“课程”类中扩展“学生”类,这意味着,“学生”类将获得所有coruse类的属性。 So, the student class does not have the courseTitle property. 因此,学生班级不具有courseTitle属性。

Second, yes, it is unnesessary - you need to do the following: 其次,是的,这是不必要的-您需要执行以下操作:

public class Course
{
    private Award courseAward;
    private String courseCode;
    public String courseTitle;
    private String courseLeader;
    private int courseDuration;
    private boolean courseSandwich;

    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 
{
    private int studentNumber;
    private String studentName;
    private int studentPhone;

    // This is where you keep the course object associated to student
    public Course studentCourse;

    public Student(int number, String name, int phone, Course course)
    {
        studentNumber = number;
        studentName = name;
        studentPhone = phone;
        studentCourse = course;
    }  
}

Example usage would be something like this: 示例用法如下所示:

Course course = new Course("ASD", "TITLE", null, "ME", 50, true);   
Student student = new Student(1, "JOHN", "5551234", course);

And then, get the course information you need from student via, ie: 然后,通过以下方式从学生那里获得所需的课程信息:

student.studentCourse.courseTitle;

Since now student.studentCourse will be a course object with all of its properties. 从现在开始,student.studentCourse将成为具有所有属性的课程对象。

Cheers, 干杯,

As mentioned, stay away from the "extends" for this. 如前所述,请远离“扩展”。 In general, you shouldn't use it unless the "is-a" relationship makes sense. 通常,除非“ is-a”关系有意义,否则不应使用它。

You should probably provide getters for the methods on the Course class: 您可能应该为Course类上的方法提供吸气剂:

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: 然后,如果Student类需要它,它将以某种方式掌握课程(这取决于您的设计),然后调用getter:

public class Student {
   private Set<Course> courses = new HashSet<Course>();

   public void attendCourse(Course course) {
       courses.add(course);
   }

   public void printCourses(PrintStream stream) {
       for (Course course : courses) {
           stream.println(course.getTitle());
       }
   }
}

Here below find out the solution of your problem and if you want to check below code on your machine then create a file named Test.java and paste the below codes: 在下面找到问题的解决方案,如果要在计算机上检查以下代码,请创建一个名为Test.java的文件并粘贴以下代码:

package com; 包com;

class Course
{
    private Award courseAward;
    private String courseCode;
    public String courseTitle;
    private String courseLeader;
    private int courseDuration;
    private boolean courseSandwich;


    public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
    {
        courseAward = award;
        courseCode = code;
        courseTitle = title;
        courseLeader = leader;
        courseDuration = duration;
        courseSandwich = sandwich;

    }

    public Award getCourseAward() {
        return courseAward;
    }

    public void setCourseAward(Award courseAward) {
        this.courseAward = courseAward;
    }

    public String getCourseCode() {
        return courseCode;
    }

    public void setCourseCode(String courseCode) {
        this.courseCode = courseCode;
    }

    public String getCourseTitle() {
        return courseTitle;
    }

    public void setCourseTitle(String courseTitle) {
        this.courseTitle = courseTitle;
    }

    public String getCourseLeader() {
        return courseLeader;
    }

    public void setCourseLeader(String courseLeader) {
        this.courseLeader = courseLeader;
    }

    public int getCourseDuration() {
        return courseDuration;
    }

    public void setCourseDuration(int courseDuration) {
        this.courseDuration = courseDuration;
    }

    public boolean isCourseSandwich() {
        return courseSandwich;
    }

    public void setCourseSandwich(boolean courseSandwich) {
        this.courseSandwich = courseSandwich;
    }
}

class Student 
{
    private int studentNumber;
    private String studentName;
    private int studentPhone;
    private Course studentCourse;
    /**
     * Constructor for objects of class Student
     */
    public Student(int number, String name, int phone, Course course)
    {
        studentNumber = number;
        studentName = name;
        studentPhone = phone;
        studentCourse = course;
    }

    public int getStudentNumber() {
        return studentNumber;
    }
    public void setStudentNumber(int studentNumber) {
        this.studentNumber = studentNumber;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public int getStudentPhone() {
        return studentPhone;
    }
    public void setStudentPhone(int studentPhone) {
        this.studentPhone = studentPhone;
    }
    public Course getStudentCourse() {
        return studentCourse;
    }
    public void setStudentCourse(Course studentCourse) {
        this.studentCourse = studentCourse;
    }
}

class Award{
    private long awardId;
    private String awardName;

    Award(long awardId, String awardName){
        this.awardId = awardId;
        this.awardName = awardName;
    }

    public long getAwardId() {
        return awardId;
    }

    public void setAwardId(long awardId) {
        this.awardId = awardId;
    }

    public String getAwardName() {
        return awardName;
    }

    public void setAwardName(String awardName) {
        this.awardName = awardName;
    }
}

public class Test{
    public static void main(String ar[]){

        // use your all classes here


    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM