this 예약어


생성된 인스턴스 스스로를 가리키는 예약어

package thisex;

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 ThisExample {
	public static void main(String[] args) {
		Birthday bDay = new Birthday();
		bDay.setYear(2000);
		System.out.println(bDay);
		bDay.printThis();
	}
}
package thisex;

class Person {
	String name;
	int age;
	
	// 기본생성자
	// this를 사용해 매개변수가 있는 생성자를 호출
	
	Person() {
//		this.name = name; --> 작성 불가
		this("이름 없음", 1);
	}
	
	// 매개변수가 있는 생성자
	Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	// 반환형은 클래스 자료형을 사용
	Person returnItSelf() {
		return this;
	}
}

public class CallAnotherConst {
	public static void main(String[] args) {
		Person noName = new Person();
		System.out.println(noName.name);
		System.out.println(noName.age);
		
		Person p = noName.returnItSelf();
		System.out.println(p);
		System.out.println(noName);
	}
}

Static 변수


클래스 내부에 선언하는 정적 변수 or 클래스 변수. 프로그램이 실행되어 메모리에 올라갔을 때 딱 한 번 메모리 공간이 할당되고 그 값은 모든 인스턴스가 공유한다.