참조 자료형

임준철·2021년 3월 14일
0

JavaAdvanced

목록 보기
7/15

참조 자료형(ReferenceDataType)

변수의 자료형

  • 기본 자료형은 사용하는 메모리가 정해져 있지만, 참조 자료형은 클래스에 따라 다르다.

참조 자료형 직접 만들어 사용하기

  • 학생 클래스에 있는 과목 이름, 과목 성적 속성을 학생클래스와 과목 클래스로 분리하고,
    과목 참조 자료형 멤버 변수를 학생에 정의하여 사용한다.

  • 예제

// Subject 클래스
public class Student {
    int stuID;
    String stuName;
    Subject korSub;
    Subject matSub;

    public Student(int stuID,String stuName){
        this.stuID = stuID;
        this.stuName = stuName;

        korSub = new Subject();
        matSub = new Subject();
    }

    public void setKoreaSubject(String subName, int subScore) {
        korSub.subName = subName;
        korSub.subScore = subScore;
    }

    public void setMathSubject(String subName, int subScore) {
        matSub.subName = subName;
        matSub.subScore = subScore;
    }
    
    public void getKoreaSubject(String subName,int subScore){
        korSub.setSubject(subName,subScore);
    }
    
    public void getMathSubject(String subName,int subScore){
        matSub.setSubject(subName,subScore);
    }

    public void showStudentScore() {
        int total = korSub.subScore + matSub.subScore;
        System.out.println(stuName+"학생의 총점은 "+total+"입니다.");
    }



}

// Subject 클래스
public class Subject {
    String subName;
    int subScore;

    public void setSubject(String subName,int subScore){
        this.subName = subName;
        this.subScore = subScore;
    }
}

// Test클래스
public class StudentTest {
    public static void main(String[] args) {
        Student studentLee = new Student(123,"lee");
        Student studentKim = new Student(456,"kim");

//        studentLee.setKoreaSubject("국어",100);
//        studentLee.setMathSubject("수학",95);
//        studentKim.setKoreaSubject("국어",99);
//        studentKim.setMathSubject("수학",80);

        studentLee.getKoreaSubject("국어",95);
        studentLee.getMathSubject("수학",100);
        studentKim.getKoreaSubject("국어",99);
        studentKim.getMathSubject("수학",80);
        
        studentLee.showStudentScore();
        studentKim.showStudentScore();

    }
}
profile
지금, 새로운 문을 열자! 문 저편에 무엇이 있을지 두렵더라도!!

0개의 댓글