평범한 연구소

[Java] this와 this() 본문

JAVA

[Java] this와 this()

soyeonisgood 2023. 2. 10. 12:05

this

인스턴스 자신을 가리키는 참조 변수

 

this()

생성자

 

 

this

class Car {
	String color; // 인스턴스 변수
	int gearType;


	Car(String color, String gearType) {
		this.color = color;
		this.gearType = gearType;
	}
}
  • this 는 생성자의 매개변수로 선언된 변수 이름과, 인스턴스 변수 이름이 같을 때 구분하기 위해 사용한다.
  • this.color 는 인스턴스 변수
  • color 는 매개변수로 정의된 지역변수
  • static 메서드에서는 this 를 사용할 수 없다.

 

``

this()

class Car {
	String color; // 인스턴스 변수
	int gearType;


	Car(String color, String gearType) {
		this.color = color;
		this.gearType = gearType;
	}
}
  • this() 는 같은 클래스의 다른 생성자를 호출할 때 사용
  • Car(String color) 생성자는 this() 를 통해 모두 Car(String color, String gearType) 생성자를 호출하는 것이다.

'JAVA' 카테고리의 다른 글

[Java] Thread 쓰레드  (0) 2023.02.13
[백준] 1235번: 학생 번호 (JAVA)  (0) 2023.02.10
[Java] 상속과 참조  (0) 2023.02.09
[JAVA] 의사코드란? (Pseudo-code, 슈더코드)  (0) 2023.02.02
[Spring|MariaDB] SQL query 로그 출력하기  (0) 2023.01.26