728x90
- 자기자신의 속성을 가리키는 또다른 이름
-
메소드 내에서 사용
-
객체 생성자내에서 다른 생성자를 호출시 사용
-
매개변수(지역변수)와 멤버변수(필드)를 구분하기 위해 멤버변수 앞에 this.를 붙여 사용
형식)
this.필드명;
this.메소드명();
this(); //생성자 호출
참고)
super.필드명
super.메소드명();
super(); //부모클래스 생성자 호출
this 예제
public class Abc {
int su;
public Abc() {
this(100);
}
public Abc(int su){
this.su = su;
}
}
Abc a = new Abc();
System.out.println(a.su);
//100 //this(100); 표기안할시 0
Abc a = new Abc(500);
System.out.println(a.su);
// su = su; 라고 칭할 시 0(지역변수만 500)
// this.su = su; 하면 500
class My {
void goodChoice(Child c) {
c.hello();
}
}
class Child {
Child( ) {
My m = new My();
m.goodChoice(this);
}
public void hello() {System.out.print("hi");}
public static void main(String[] args) {Child c = new Child();}
}
- Child 클래스의 생성자에서 My 클래스를 객체생성하고 참조변수 m을 통해 My클래스의 메소드 goodChoice를 호출한다. 이 때 goodChoice의 매개변수를 클래스 Child c로 받기때문에 this를 사용하여 Child의 속성을 전달하여준다.
- 만약 My에 new Child()를 사용하게되면 new 메모리 할당으로 인해 새로운 주소가 생기게 되고 각각 다른 주소를사용하게되어 오류가 발생할 수 있다.
'Web develop > JAVA' 카테고리의 다른 글
[JAVA] 자바빈즈(JavaBeans) (0) | 2019.04.24 |
---|---|
[JAVA] 자바 인터페이스 형식, 사용 예시 (0) | 2019.04.23 |
[JAVA] 자바 접근제한자(AccessControl) (0) | 2019.04.21 |
[JAVA] 자바클래스 생성자(Constructor) (0) | 2019.04.21 |
[JAVA] 객체지향의 특징 (상속, 캡슐화, 다형성) (0) | 2019.04.21 |