변수의 자료형에는 기본 자료형과 참조 자료형이 있다.
지역변수는 수동 초기화, 멤버변수(클래스변수, 인스턴스변수)는 자동 초기화 된다.
💡 개념은 변수의 종류와 초기화 정리 해놓은거 참고하기
[Subject 클래스]
package ch09;
public class Subject {
String subjectName;
int score;
int subjectId;
}
클래스형으로 선언한 Subject는 참조형 변수이다.
[Student 클래스]
package ch09;
public class Student {
int studentId;
String studentName;
Subject korea = new Subject();
Subject math = new Subject();
Student(int studentId, String StudentName){
this.studentId = studentId;
this.studentName = studentName;
}
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 showScoreInfo() {
int total = korea.score + math.score;
System.out.println(studentName + "학생의 점수는 " + total + "점입니다.");
}
}
Subject 타입의 참조형 변수(korea, math)를 사용하기 위해 인스턴스를 생성해주었다. 강의에선 선언과 초기화를 따로 해주었는데 헷갈려서 한줄로 합쳐서 작성했다.
Student 클래스는 참조형 변수가 아닌 객체이다.
[SubjectTest 클래스]
package ch09;
public class SubjectTest {
public static void main(String[] args) {
Student studentLee = new Student(100, "Lee");
studentLee.setKoreaSubject("국어", 100);
studentLee.setMathSubject("수학", 99);
Student studentKim = new Student(100, "Lee");
studentKim.setKoreaSubject("국어", 50);
studentKim.setMathSubject("수학", 65);
studentLee.showScoreInfo();
studentKim.showScoreInfo();
}
}
Student 객체를 사용해서 studentLee, studentKim 두 개의 인스턴스 생성
[실행 결과]