서로 상호작용하며 의존함
상태
와행위
가 있는식별 가능
한 모든 대상
class 클래스명 {
멤버 변수 정의
메서드 정의
}
✅ new 클래스명()
: 생성자 메서드
인스턴스
라고 표현한다. 메모리 공간도 용도에 따라 나뉘어짐
객체가 생성되는 메모리 공간 =>힙
public class Student {
int id;
String name;
String subject;
public Student(int _id, String _name, String _subject) {
this.id = _id;
this.name = _name;
this.subject = _subject;
}
void showInfo(){
System.out.printf("id=%d, name=%s, subject=%s\n", id, name, subject);
}
}
public class Ex01{
public static void main(String[] args){
Student s1 = new Student();
// 힙에 메모리 생성(객체는 힙에 생성됨)
// s1은 참조 변수이고 주소값을 가지며, 스택에 생성
s1.id =1000;
s1.name = "학생1";
s1.subject = "과목1";
}
}
기본자료형(String Integer 등등)을 제외한 변수는
참조 변수
라고 표현 함
기본 형을 제외한 모든 자료형은 참조 자료형
참조 변수는 모두 동일한 자료형임 (4byte)
why? 주소값만 가지면됨 참조만 하기 때문에
public class StudentMain {
public static void main(String[] args) {
Student s1 = new Student(1000, "학생1", "과목1");
s1.showInfo();
Student s2 = new Student(2000, "학생2", "과목2");
s2.showInfo();
Student s3 = s2; // 주소값만 복사 한 것
s3.id = 1001;
s3.name = "(수정)학생";
s3.showInfo();
s2.showInfo();
System.out.println(System.identityHashCode(s1)); // 가상의 주소값
System.out.println(System.identityHashCode(s2)); // 가상의 주소값
System.out.println(System.identityHashCode(s3)); // 가상의 주소값
}
}
id=1000, name=학생1, subject=과목1
id=2000, name=학생2, subject=과목2
id=1001, name=(수정)학생, subject=과목2
id=1001, name=(수정)학생, subject=과목2
284720968
189568618
189568618
가상의 주소이며 물리적으로 돌아갈 때 진짜 주소값을 참조함
System.identityHashCode()
클래스 로더 -> Class 클래스 객체 생성(클래스의 정보)
정보를 확인해서 객체를 생성함(정적변수로 접근할 수 있음)
힙 영역엔 가비지 컬렉터가 있음
데몬쓰레드라고도 함
static : 정적인
정적(static) 메모리 : 고정된 메모리
정적 변수는 데이터 영역에 할당되는 변수
동적(dynamic) 메모리 : 생성과 소멸을 반복하는 메모리(스택[임시메모리]
, 힙)
public class Student {
static int id; // 정적변수
String name;
String subject;
public Student(int _id, String _name, String _subject) {
this.id = _id;
this.name = _name;
this.subject = _subject;
}
void showInfo(){
System.out.printf("id=%d, name=%s, subject=%s\n", id, name, subject);
}
}
public class StudentMain {
public static void main(String[] args) {
Student s1 = new Student(1000, "학생1", "과목1");
s1.showInfo();
Student s2 = new Student(2000, "학생2", "과목2");
s2.showInfo();
s1.showInfo();
}
}
id=1000, name=학생1, subject=과목1
id=2000, name=학생2, subject=과목2
id=2000, name=학생1, subject=과목1
static은 모든 인스턴스 자원이 공유한다.
그러나 실행하기 전에는 정적변수인지 동적변수인지 알 수 없음
따라서 정적변수의 경우 클래스명에서 바로 접근하는 것을 권장한다.
public class StudentMain1 {
public static void main(String[] args) {
Student.id=1000; // 객체와 상관없이 사용 가능
}
}