Java/Java 올인원 패키지
4. 참조 자료형 (reference data type)
GrapeMilk
2020. 3. 14. 01:16
Goal
- 참조 자료형을 이해한다
- 참조 자료형을 직접 생성하여 사용해본다.
1. 참조 자료형
- 변수의 자료형에는 기본 자료형과 객체로 이루어진 참조 자료형 2가지가 있음.
- 참조 자료형은 클래스형으로 변수를 선언함. ex) String name;
- 기본 자료형은 사용하는 메모리가 정해져 있지만, 참조 자료형은 클래스에 따라 다름.
2. 참조 자료형 구현
- 학생 클래스 (Student)에 있는 과목 이름, 과목 점수 속성을 과목 클래스(Subject)로 분리한다.
- 과목(Subject)클래스를 참조 자료형으로 학생(Student)클래스에 정의하여 사용함.
- 참조 자료형의 구현을 통해 각 클래스마다 하나의 속성을 정해서 분리함으로써(학생이면 학생클래스, 과목이면 과목클래스) 프로그램을 더 깔끔하게 작성할 수 있음.
예제 1) StudentTest.java
- Student 클래스와 Subject 클래스를 테스트 하기 위해 작성한 파일.
public class StudentTest {
public static void main(String[] args) {
Student studentLee = new Student(100, "Lee");
studentLee.setKoreaSubject("국어", 100);
studentLee.setMathSubject("수학", 95);
Student studentKim = new Student(101, "kim");
studentKim.setKoreaSubject("국어", 80);
studentKim.setMathSubject("수학", 95);
studentLee.showStudentScore();
studentKim.showStudentScore();
}
}
예제 2) Student.java
- 참조형 변수는 클래스 타입이므로 클래스의 기능들을 사용하기 위해 초기화(인스턴스화)를 해야 한다.
- 보통 참조형 변수를 사용하고자하는 클래스의 생성자에 초기화코드를 같이 작성한다. (Student 생성시 Subject 타입의 참조형 변수들도 같이 생성된다)
//Student와 관련된 맴버들을 Student 클래스에 정의
public class Student {
int studentID;
String studentName;
Subject korea; //참조 자료형 타입으로 변수를 선언. Subject 클래스가 참조 자료형 타입으로, Student의 맴버가 됨.
Subject math;
public Student(int id, String name) {
studentID = id;
studentName = name;
korea = new Subject(); //인스턴스를 생성하면서, 참조 자료형 초기화.
math = new Subject();
}
public void setKoreaSubject(String name, int score) {
korea.subjectName = name;
korea.score = score;
}
public void setMathSubject(String name, int score) {
math.subjectName = name;
math.score = score;
}
public void showStudentScore() {
int total = korea.score + math.score;
System.out.println(studentName + " 학생의 총점은 " + total + " 점 입니다. " );
}
}
예제 3) Subject 코드
//과목과 관련된 맴버들을 Subject에 정의
public class Subject {
String subjectName;
int score;
}