class BirthDay {
int day;
int month;
int year;
public void setYear(int year) {
this.year = year;
}
public void printThis() {
System.out.println(this);
}
}
public class Example {
public static void main(String[] args) {
BirthDay bDay = new BirthDay();
bDay.setYear(2000);
System.out.println(bDay);
bDay.printThis();
}
}
this
와 dDay 클래스
는 모두 생성된 BirthDay 클래스를 가르킴Person() {
this("이름 없음", 1);
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
this
를 사용해 Person(String, int)
생성자 호출Person returnItSelf() {
return this;
}
this
를 사용하면 자신의 주소 값을 반환할 수 있음public class Student {
public static int serialNum = 1000;
public int sutdentId;
public String studentName;
public int grade;
public String address;
public String getStudentName() {
return studentName;
}
public void setStudentname(String name) {
studentName = name;
}
}
public class Test {
public static void main(String[] args) {
Student student1 = new Student();
student1.setStudentName("cheoljin");
System.out.println(student1.serialNum); // 1000
student1.serialNum++;
Student student2 = new Student();
student2.setStudentName("cheoljinpark");
System.out.println(student2.serialNum); //1001
System.out.println(student1.serialNum); //1001
}
}
static
으로 선언된 변수 serialNum을 공유함변수 유형 | 선언 위치 | 사용 범위 | 메모리 | 생성과 소멸 |
---|---|---|---|---|
지역 변수 (로컬 변수) | 함수 내부에 선언 | 함수 내부에서만 사용 | 스택 | 함수가 호출될 때 생성되고 함수가 끝나면 소멸함 |
멤버 변수 (인스턴스 변수) | 클래스 멤버 변수로 선언 | 클래스 내부에서 사용하고 private이 아니면 참조 변수로 다른 클래스에서 사용 가능 | 힙 | 인스턴스가 생성될 때 힙에 생성되고, 가비지 컬렉터가 메모리를 수거할 때 소멸됨 |
static 변수 (클래스 변수) | static 예약어를 사용하여 클래스 내부에 선언 | 클래스 내부에서 사용하고 private이 아니면 클래스 이름으로 다른 클래스에서 사용 가능 | 데이터 영역 | 프로그램이 처음 시작할 때 상수와 함께 데이터 영역에 생성되고 프로그램이 끝나고 메모리를 해제할 때 소멸됨 |
public class Company {
private Company() {}
}
public static Company {
private static Company instance = new Company(); // 유일한 인스턴스
private Company() {}
}
public static Company {
private static Company instance = new Company(); // 유일한 인스턴스
private Company() {}
public static Company get Instance() {
if(instance == null) {
instance = new Company(); // 인스턴스가 없으면 생성
}
return instance; // 유일하게 생성한 인스턴스 반환
}
}
public class CompanyTest {
public static void main(String[] args) {
Company myCompany1 = Company.getInstance();
Company myCompany2 = Company.getInstance();
System.out.println(myCompany1 == myCompany2); // 두 변수가 같은 주소인지 확인
//true
}
}