this 레퍼런스
this
this는 자바의 중요한 키워드로서 단어 뜻 그대로 객체 자신을 가리키는 레퍼런스이다.
this의 기초 개념
현재 실행되고 있는 인스턴스의 특정 필드를 지정할 때 사용된다.
public class Circle{
int radius;
public Circle(int r) { this.radius = r; } //멤버 radius를 접근
public int getRadius() { return radius; } //return this. radius;와 동일 } |
this의 필요성
public Circle(int radius) { radius = radius; } |
여기서 2개의 radius는 모두 매개변수 radius를 접근하기 때문에, 멤버 radius를 변경하지 못한다.
생성자나 메소드의 매개변수 이름을 의미 있는 이름으로 정해주다 보면 멤버변수 이름과 겹치게 된다.
이 때 멤버변수 자신을 구별할 목적으로 사용된다.
public Circle (int radius) { this.radius = radius; } public Circle getMe( ) { return this;} //getMe()메소드는 객체 자신의 레퍼런스 리턴 |
this()
생성자가 중복되어 있을 때 또다른 생성자를 호출 하고자할 때 사용한다.
class Binu{
int age; int tall;
Binu() { this(3,40); }
Binu(int age) { this.age =age; tall=0; }
Binu(int age, int tall) { this.age =age; this.tall=tall; } }
|
this()사용 시 주의할 점
-this()는 반드시 생성자 코드에서만 호출할 수 있다.
-this()는 반드시 같은 클래스 내 다른 생성자를 호출할 때 사용된다.
-this()는 반드시 생성자의 첫번째 문장이 되어야 한다.
'프로그래밍 > JAVA' 카테고리의 다른 글
[JAVA] final (1) | 2018.08.20 |
---|---|
[JAVA] String 타입 (8) | 2018.08.20 |
[JAVA]상속-부모클래스, 자식클래스 (5) | 2018.08.18 |
[JAVA]접근 지정자를 알아보자! (2) | 2018.08.17 |
[JAVA] 객체 지향의 4가지 특징을 알아보자! (10) | 2018.08.16 |