Back-End/Java
[Java] 참조 자료형 변수
nanee_
2021. 8. 30. 13:07
728x90
반응형
SMALL
변수의 자료형
- 기본 자료형
: int, long, float, double 등의 데이터타입으로 변수를 선언한다.
사용하는 메모리의 크기가 정해져 있다.
- 참조 자료형
: String, Date 등의 클래스형으로 변수를 선언한다.
클래스에 따라서 메모리의 크기가 달라진다.
사용할 때에는 해당 변수에 대해 생성을 해야한다.
(String 클래스는 예외적으로 생성하지 않고 사용할 수 있다.)
참조 자료형 정의하고 사용
- class Subject : 과목 이름, 과목 점수
- class Student : 학번, 이름, 국어과목, 수학과목
- class StudentTest : Student 클래스를 new해서 학생 별로 점수를 초기화한다.
public class Subject{
String subjectName;
int score;
int subjectId;
}
public class Student{
int studentId;
String name;
Subject korea;
subject math;
// 생성자
public Student(int studentId, String name){
this.studentId = studentId;
this.name = name;
korea = new Subject(); // Subject 클래스를 korea로 인스턴스화
math = new Subject(); // Subject 클래스를 math로 인스턴스화
}
// 메서드 - Korea 점수
public void setKoreaSubject(String name, int score){
// korea 객체의 멤버변수에 접근해 초기화
korea.subjectName = name;
korea.score = score;
}
// 메서드 - Math 점수
public void setMathSubject(String name, int score){
// math 객체의 멤버변수에 접근해 초기화
math.subjectName = name;
math.score = score;
}
}
public class StudentTest{
public static void main(String[] args){
Student student1 = new Student(100, "NANA");
student1.setKoeraSubject("국어", 93);
student1.setMathSubject("수학", 96);
Student student2 = new Student(101, "Jeno");
student2.setKoreaSubject("국어", 100);
student2.setMathSubject("수학", 88);
}
}
728x90
반응형
LIST