[Java] 클래스 - this와 this()

chael_lo·2021년 5월 16일
0

Java

목록 보기
13/52

this

자기 자신을 뜻하며, 자바에서는 클래스 안에서 this 참조 변수를 사용하여 인스턴스 변수에 접근할 수 있다.(가독성을 높임)

this를 사용하면 메서드의 인수나 변수에 필드와 같은 이름을 붙여도 구분이 가능하다.

class Circle{
private int r;
	public void setData(int r) {//매개변수 r
		this.r = r;//Circle의 r
	}
}	

생성자 및 세터 메서드에서 필드에 접근할 수 있다.

class Super1{
  private String title;
  private String email;
  //생성자 선언
  public Super1(String title) {
      this.title = title;//Super1의 title
  }

  //세터 메서드 선언
  public void setEmail(String email) {
      this.email = email;//Super1의 email
  }
}

this 스스로의 참조를 반환할 수 있다.

새로운 인스턴스를 만드는게 아니라 클래스의 주소를 반환한다.

public Super1 getInstance() { 
	return this; 
}

//동일한 결과 출력
Super1 address = new Super1();
address.getInstance();

this()

this()는 생성자 내부에서만 사용할 수 있고, 같은 클래스의 다른 생성자를 호출할 때 사용한다.

//생성자
Car(String name, int year, String color) {
	this.name = name;
	this.year = year;
	this.color = color;
}

Car() {
	this("이름이다", 1993);// 다른 생성자를 호출
}
profile
천천히 꾸준히

0개의 댓글