Burninghering's Blog
article thumbnail

참조 자료형

변수의 자료형

 

  • 클래스를 타입으로 변수 선언
  • 기본 자료형은 사용하는 메모리의 크기가 정해져 있지만, 참조 자료형은 클래스에 따라 할당되는 메모리가 다르다
  • String 클래스는 예외적으로 생성하지 않고 사용할 수 있다.

 

참조 자료형 정의하여 사용하기

  1. 학생이 수강한 과목들에 대한 성적을 산출하려고 하는데, 학생 클래스 속성에 모든 과목이 있으면, 모든 과목을 듣지 않은 학생들은 어떻게 할 것인가?
  2. 학생(Student)과 과목(Subject)에 대한 클래스를 따로 분리하고 -> Subject 클래스를 활용하여 수강한 과목들을 변수의 타입으로 선언

선언된 Subject 변수는 생성된 인스턴스가 아니므로, Student의 생성자 안에서 생성하여 사용

 

그러니까...

학생 클래스에, 참조 자료형으로 모든 "과목"들을 선언해준다.

속성 변수로 모든 "과목"을 선언해버리면, 수강하지 않은 과목들에도 생성자 파라미터로 초기화를 해줘야하니까,

참조 자료형으로 만든 변수(과목)를 set하는 함수들만 따로 모든 과목에 대해 만들어주면,

학생 클래스로 만든 각각의 학생 객체가 각각 수강한 과목들에 대해 총 합산을 구할 수 있다.

그러므로 결론은

public Student(int id,String name,int score){
		studentID = id;
		studentName = name;
        	mathScore = score;	
}
public Student(int id,String name,int score){
		studentID = id;
		studentName = name;
       		koreaScore = score;	
}
public Student(int id,String name,int score1,int score2){
		studentID = id;
		studentName = name;
      	 	koreaScore = score1;
       		mathScore = score2;
}

 

생성자를 여러 개 만들어야 하니까 참조 자료형 변수를 쓰는 것이다!!(+참조 자료형 변수를 set하는 함수도 사용)

생성자를 여러 개 만들면 힘드니까 참조 자료형 변수를 써서 쉽게 코딩을 하자?

 

 

참조 자료형 변수는 생성해서 써야하고,
참조 자료형으로 분리하는 것이, 좀 더 각각 객체에 대한 역할과 기능을 분명히 하는 것에 도움이 된다.

 

 

최종 코드 예제

Student.java

package ch09;

public class Student {
	int studentID;
	String studentName;
	
	Subject korea;
	Subject math;
	
	Student(int studentID, String studentName){
		this.studentID=studentID;
		this.studentName=studentName;
		
		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 showScore() {
		int total=korea.score+math.score;
		System.out.println(studentName+"학생의 총점은 "+total+"점 입니다.");
	}
}

Subject.java

package ch09;

public class Subject {
	String subjectName;
	int score;
	int subjectID;
}

SubjectTest.java

package ch09;

public class SubjectTest {
	public static void main(String[] args) {
		Student studentLee = new Student(100,"Lee");
		studentLee.setKoreaSubject("국어",100);
		studentLee.setMathSubject("수학",100);
		
		studentLee.showScore();
	}
}

 

장엄한 결과

profile

Burninghering's Blog

@개발자 김혜린

안녕하세요! 반갑습니다.