프로그래밍 언어/JAVA
this, this() 이해하기
리그캣
2018. 1. 31. 14:10
this 와 this()는 다르다
super 와 super() 또한 다르다
this는 현재 클래스의 인스턴스를 가리킨다.
super는 부모 클래스를 가리킨다.
현재 클래스의 인스턴스에 있는 속성이나 함수를 제어하려면 this.setName()을 하고 부모 클래스의 함수를 호출하고 싶으면 super.setName()을 입력한다.
this 사용할때 예제
- 클래스의 속성과 매개변수의 이름이 같을때
public
class
생성자 {
public
String name;
public
String color;
public
double
weight;
public
Fruit(String name, String color,
double
weight) {
name = name;
color = color;
weight = weight;
}
public
static
void
main(String[] args) {
Fruit banana =
new
Fruit(
"banana"
,
"yellow"
,
5.0
);
System.out.println(
"name : "
+ banana.name);
System.out.println(
"color : "
+ banana.color);
System.out.println(
"weight : "
+ banana.weight);
}
}
위에 처럼 작성하게 되면 매개 변수의 이름과 Fruit 에 내에 지역변수 이름이 같기 때문에 Fruit 객체의 name 속성에 값이 저장되지 않는다. 이렇기 때문에 Fruit 인스턴스를 가리키는 this 키워드를 사용해야 한다.
public
class
Fruit {
public
String name;
public
String color;
public
double
weight;
public
Fruit(String name, String color,
double
weight) {
this
.name = name;
this
.color = color;
this
.weight = weight;
}
public
static
void
main(String[] args) {
Fruit banana =
new
Fruit(
"banana"
,
"yellow"
,
5.0
);
System.out.println(
"name : "
+ banana.name);
System.out.println(
"color : "
+ banana.color);
System.out.println(
"weight : "
+ banana.weight);
}
}
this() 사용 예제
- 오버로딩된 다른 생성자 호출할때
this()는 자기자신의 생성자를 호출함으로서 생성자의 초기화 과정을 반복하지 않아도 된다.
class
UpperClass {
int
x;
int
y;
public
UpperClass() {
x =
10
;
y =
20
;
}
public
UpperClass(
int
x) {
this
();
// 자신의 클래스 public UpperClass() 생성자 호출
this
.x = x;
}
public
UpperClass(
int
x,
int
y) {
this
(x);
// 자신의 클래스 public UpperClass(int x) 생성자 호출
this
.y = y;
}
}
출처: http://mainia.tistory.com/85 [녹두장군 - 상상을 현실로]