this
-> 필드와 매개변수의 이름이 비슷할 경우 구분하기 위해 사용되며, 생략이 가능하다. this. 필드 형태로 사용된다. 그리고 this()를 사용하여 다른 생성자를 호출할 수 있다.
Ex)
- this를 생략하여 코드를 작성한 경우
public class Circle{
int radius;
public Circle() {
radius = 1;
}
public Circle(int r) {
radius = r;
}
double getArea() {
return 3.14 * radius * radius;
}
public static void main(String[] args) {
...
}
}
- this를 사용하여 코드를 작성한 경우
public class Circle{
int radius;
public Circle() {
this.radius = 1;
}
public Circle(int r) {
this.radius = r;
}
double getArea() {
return 3.14 * this.radius * this.radius;
}
public static void main(String[] args) {
...
}
}
* 다른 생성자를 호출하기 위해 this()를 사용할 경우
- 생성자 내에서만 사용이 가능
- 반드시 생성자 코드의 제일 처음에 수행
Ex)
public class Car {
String company = "기아자동차"; //필드
Strinf model;
Strinf color;
int maxSpeed;
public Car() {} //기본생성자
public Car(String model) {
this(model, null, 100) //다른 생성자 호출
}
public Car(String model, String color) {
this(model, color, 100) //다른 생성자 호출
}
public Car(String model, String color, int maxSpeed) {
this.model = model;
this.color = color;
this.maxSpeed = maxSpeed;
}
public static void main(String[] args) {
...
}
}
다음 글에서는 업, 다운 캐스팅과 instanceof 연산자에 대해 설명하겠습니다.
감사합니다!
2021.07.08
'JAVA' 카테고리의 다른 글
[자바] 상속 (0) | 2021.07.09 |
---|---|
[자바] 업캐스팅, 다운캐스팅 / instanceof 연산자 (0) | 2021.07.08 |
static멤버 , non - static 멤버 (0) | 2021.07.07 |
힙/스택 영역 표현 (1) (0) | 2021.07.06 |
접근지정자 / setter, getter 메소드 (0) | 2021.07.05 |