* this
- 해당 객체를 지칭하는 키워드
- 해당 멤버변수에 접근할때 일반 지역변수와 구분하기 위해 사용된다
- 특정 객체 내에서 현재 객체 자신을 의미하는 참조변수
- 자신이 객체가 되어 메모리내에 존재할 자신의 위치값(reference)을 기억하고 있음.
- 메소드 내에서만 사용됨.
- static 메소드에서는 사용할 수 없음.
- 멤버변수와 지역변수를 구별해야 할때 멤버변수 앞에서 this를 붙여서 사용
* this(), this(전달인자)
- 현재 객체의 생성자를 의미
- this(); 생성자 함수를 가르키는 대명사
- this(); 일반메소드에서는 생성자 호출 불가능
- 생성자에서 다른 생성자를 호출할 때 사용.
- 생성자의 이름으로 클래스 이름 대신 this를 사용
- 주의할 점 : 한 생성자에서 다른 생성자를 호출할 때는 반드시 첫 행에 정의해야 함.
오류 발생
파일명 : ThisEx.java
package oop2;
class City
{
String name;
String sido; //광역시, 특별시
int peple; //인구수
public City() {
System.out.println("기본생성자");
initCity();
}
public City(String name) {
this("제주","특별자치도");
this.name = name;
}
public City(String name, String sido) {
this.name = name;
this.sido = sido;
}
public City(String name, String sido, int peple) {
this(); //기본생성자 호출
this.name = name;
this.sido = sido;
this.peple = peple;
}
void initCity()
{
System.out.println("대한민국");
//City(); 생성자함수 호출. 에러
//this(); 생성자 함수를 가르키는 대명사
//this(); 일반메소드에서는 생성자 호출 불가능
}
}
public class ThisEx {
public static void main(String[] args) {
City korea=new City();
korea.initCity();
//this() 기본생성자 호출
City seoul=new City("서울","특별시",2000);
//this(전달인자) 생성자 호출
City jeju=new City("test");
System.out.println(jeju.sido); //특별자치도
System.out.println(jeju.name); //test
Integer n=new Integer("123");
int p=n;
}
}
'..열심히 공부하세.. > JAVA 문법' 카테고리의 다른 글
[22] final 키워드 (0) | 2012.04.27 |
---|---|
[21] static 예약어 (0) | 2012.04.27 |
[19] 변수의 유효범위 (Scope) (0) | 2012.04.26 |
[18] 생성자 함수 (0) | 2012.04.26 |
[17] 메소드 오버로딩 (0) | 2012.04.25 |