클래스(static 코드) —— 생성(인스턴스 화) ——> 인스턴스(객체)
클래스 생성하기
클래스를 사용하기 위해서는 클래스를 생성하여야 함
new 예약어를 이용하여 클래스 생성
클래스형 변수이름 = new 생성자;
Student studentA = new Student(); // 하나의 객체가 생성, Student → 참조형 데이터 타입 studentA → 참조 변수
public class Student {
int studentID;
String studentName;
int grade;
String address;
public void showStudentInfor() {
sysout(studentName + "," + address);
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String name) {
studentName = name;
}
//jvm이 불러줌 그래서 main이 먼저 수행
public static void main(String[] args) {
Student studentLee = new Student(); //생성자, heap메모리에 생성됨, studentLee는 참조변수
studentLee.studentName = "이순신";
studentLee.studentID = 100;
studentLee.address = "서울시 영등포구 여의도동";
Student studentKim = new Student();
studentKim.studentName = "김유신";
studentKim.studentID = 101;
studentKim.address = "미국 산호세";
studentLee.showStudentInfor();
studentKim.showStudentInfor();
}
}
인스턴스와 힙(heap) 메모리
하나의 클래스 코드로부터 여러 개의 인스턴스를 생성
인스턴스는 힙(heap)메모리에 생성됨
각각의 인스턴스는 다른 메모리에 다른 값을 가짐
new라는 키워드로 heap 메모리가 생성된다
하나의 인스턴스가 생성이 되면 독립적인 공간이 heap에 잡힌다
(stack메모리는 지역변수들이 자리를 잡는 곳)
오른쪽 힙 메모리에 studentId, studentName, grade, address가 있는거임
그래서 studentLee 하고 . 눌렀을때 뜸
studentLee에서 나오면 화살표는 주소값을 가리키는 거임(참조 변수는 내부적으로 주소를 가리키고 있다.)
힙 메모리는 동적으로 할당됨
참조 변수와 참조 값
참조 변수 : 인스턴스 생성시 선언하는 변수
참조 값 : 인스턴스가 생성되는 힙 메모리 주소
참조 변수를 이용한 참조 값 확인 코드
생성자
생성자의 용도 : 내가 처음 이 객체를 생성하면서 해야될 일을 구현하는 것
ex) 이 학생이 생성될때 아이디와 이름이 생성이 되야한다.
public Student(int id, String name) {
studentID = id;
studentName = name;
}
public static void main(String[] args) {
Student studentLee = new Student(100,"이순신");
}
생성자 오버로딩(필요에 의해 생성자 추가 하는 경우 여러 개의 생성자가 하나의 클래스에 있음)
public Student(int id, String name) { //아이디와 이름을 매개변수로 입력받는 생성자
studentID = id;
studentName = name;
}
public Student() {} //디폴트 생성자
public static void main(String[] args) {
Student studentLee = new Student();
}
생성자는 인스턴스를 초기화 할 때의 명령어 집합
생성자의 이름은 그 클래스의 이름과 같음
생성자는 메소드가 아님. 상속되지 않으며, 리턴 값을 없음
디폴트 생성자
하나의 클래스에는 반드시 적어도 하나 이상의 Constructor이 존재
프로그래머가 Constructor를 기술하지 않으면 Default Constructor가 자동으로 생김 (컴파일러가 코드에 넣어 줌)
Default Constructor는 매개 변수가 없음
Default Constructor는 수현부가 없음
만약 클래스에 매개변수가 있는 생성자를 추가하면 디폴트 생성자는 제공되지 않음
https://www.youtube.com/watch?v=oonYQa82MU4&list=PLG7te9eYUi7typZrH4fqXvs4E22ZFn1Nj
'Java' 카테고리의 다른 글
2-5 클래스와 객체2 (1) - this (0) | 2024.03.14 |
---|---|
2-4 클래스와 객체1 (4) - 참조 자료형, private (0) | 2024.03.14 |
2-2 클래스와 객체1 (2) - 메서드와 함수 (0) | 2024.03.13 |
2-1 클래스와 객체1 (1) - 객체와 클래스 (0) | 2024.02.25 |
1. 자바 기본 익히기 (0) | 2024.02.21 |