2012-06-28 6 views
6

나는 시험에 대한 실습으로 몇 가지 일을하고있다. 그러나 나는 내 머리를 돌릴 수없는 한 가지 점은 다른 반에서 한 반에 속한 변수를 사용하고 있다는 것이다.한 클래스의 변수를 Java의 다른 변수에서 사용하는 방법은 무엇입니까?

나는 Course 클래스와 Student 클래스가 있습니다. 클래스 코스는 모든 다른 코스를 저장하며, 단순히 수업에서 클래스 이름을 사용하는 것입니다. 여기

내 코스 클래스입니다 :

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

} 

내가 과정에서 '를 확장'사용하여 수정 있습니까? 아니면 이것은 불필요한가요?

Student 용 생성자에서 Course 클래스의 'courseTitle'을 'studentCourse'변수에 할당하려고합니다. 그러나 나는 이것을 어떻게 수행 하는지를 간단히 생각할 수 없다!

미리 도움을 주셔서 감사합니다. 나는 당신의 의견을 기다리고 있습니다!

감사합니다.

답변

4

이 학생이 아니므로 학생이 아니므로 해당 클래스 간의 상속은 잘못된 생각 일 수 있습니다.

4

공개로 선언해야합니다.

더 나은 방법은 비공개로 유지하고 해당 변수에 대한 공용 getter를 코딩하는 것입니다. 예를 들면 :

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

CourseStudent을 연장해서는 안된다. courseTitle 필드에 Course에 액세스하려는 경우 Course 개체에 대한 참조를 Student에 전달한 다음 course.CourseTitle을 수행해야합니다.

2

클래스의 개인 속성을 다른 속성에 액세스 할 수 없습니다. 이것은 OOP의 주요 원칙 중 하나 인 캡슐화입니다. 이러한 속성에 대한 액세스 방법을 제공해야하며 클래스 외부에 게시하고 싶습니다. 일반적인 접근 방식은 클래스를 변경하지 못하게하려는 경우 setter/getters - getters 만 사용합니다. 여기를보세요 : http://en.wikipedia.org/wiki/Mutator_method#Java_example

11

코스 내에서 '확장'을 사용하는 것이 맞습니까? 아니면 이것은 불필요한가요? 불행하게도

하지, 당신이 당신의 상속이 올바른지 여부 알고 는-A 확장 대체합니다. 코스는 학생입니까? 내 대답은 아니오 야. 어떤 당신의 CourseStudent

이 학생은 따라서 Student 클래스 유형 Course의 멤버 변수를 가질 수하는 Course에 참석할 수 확장 안 의미한다. 모델에서 지정한 경우 (학생이 여러 과목을들을 수 있음) 코스 목록을 정의 할 수 있습니다.여기

은 샘플 코드입니다 : 이제

public class Student{ 
    //.... 
    private Course course; 
    //... 
    public void attendCourse(Course course){ 
     this.course = course; 
    } 
    public Course getCourse(){ 
     return course; 
    } 
} 

, 다음과 같은 수 있습니다 :

Student bob = new Student(...); 
Course course = new Course(...); 
bob.attendCourse(course); 
2

그것은 임의의 클래스를 확장하는 이해가되지 않습니다. 학생은 코스가 아니거나 그 반대 일 수도 있으므로 그렇게 확장 할 수는 없습니다.

당신이해야 할 것은 :

먼저 코스를 만들 :

 aStudent.setCourse(aCourse.title); 
:

 Student aStudent = new Student(..); 

가 학생에게 코스를 할당 :

 Course aCourse = new Course(..); 

은 학생을 만들

2

StudentCouse으로 확장하면 같은 종류가 아니기 때문에 확장됩니다. 하나의 클래스를 다른 클래스로 확장하는 것은보다 일반적인 (의미에서) 하나의 클래스를 전문화 할 때 발생합니다.
이 솔루션은 Student 생성자의 인수로 courseTitle을 통과하는 것입니다

2

여기에 3 별도의 객체, 교육 과정, 학생 및 등록이 있어야합니다. 등록은 학생과 코스를 연결하고 코스에는 많은 학생이 있으며 학생은 여러 코스에 등록 할 수 있습니다. 그들 중 누구도 서로를 확장 시켜서는 안됩니다.

+0

이 경우에 대한 많은 매핑 조인 테이블 (등록 개체)이 필요하다고 생각하지 않습니다. (기존의 데이터베이스에서 유지해야 할 필요가 없다면) –

+0

@ 존 : 그렇습니다. 그러나 OP는 분명히 OO를 오용하는 끔찍한 사례에 노출되어 있기 때문에이를 모델링하기위한보다 철저한 대안을 보여주고 싶습니다. –

+0

이 좋습니다. –

2

어쩌면 학생에게 코스 이름을 추가 할 필요가 없을 수도 있습니다. 내가 할 일은 코스에서 일부 데이터 구조에 학생들을 추가하는 것입니다. 이것은보다 깨끗하고 Course와 Student 간의 결합을 줄입니다. 이것은 또한 한 과목 이상을 수강 할 수 있도록합니다. 예를 들면 : 당신은 의미 코스 클래스에서 학생 클래스를 확장하는

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

} 먼저

2

,

, 학생 클래스는 모든 coruse 클래스 속성을 가져옵니다. 따라서 학생 클래스에는 courseTitle 속성이 없습니다.

둘째, 그래, 그것은 unnesessary - 당신은 다음을 수행해야합니다

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

사용 예제는이 같은 것입니다 :

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

를 그리고, 당신이 필요로하는 과정 정보를 얻을 수 학생에게서, 예 :

student.studentCourse.courseTitle; 

지금부터 student.studentCourse는 코스가 될 것입니다. 모든 속성을 가진 객체.

건배, 언급 한 바와 같이

1

는이에 대해 "확장"멀리. 일반적으로, "is-a"관계가 이치에 맞지 않으면 사용하지 말아야합니다.

당신은 아마 코스 클래스의 메소드에 대한 게터를 제공해야

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

그리고 학생 클래스가 있음을 필요로하는 경우 다음 어떻게 든에서 당신에게 달려 과정의 보류를 (얻을 것이다 당신의 디자인), 및 호출 게터 :

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

여기 아래에 문제의 해결책을 찾아 당신이 당신의 컴퓨터에서 코드 아래 확인하려면 다음 Test.java라는 파일을 만들고 아래 코드를 붙여 넣습니다

package 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 


    } 
} 
관련 문제