[Java] this vs this(), super vs super()
2021. 8. 2. 22:25ㆍ카테고리 없음
자바에는 this와 this(), super와 super()가 있는데 비슷해보이지만, 완전히 다르다.
this() : 생성자를 말한다.
public class Rect{
private int x2,y2;
public Rect(int x){
x2 = x;
}
public Rect(int x, int y) {
// 다른 생성자를 호출해준다.
this(x);
}
}
this : 인스턴스 자기 자신을 가르키는 키워드
public class Rect{
private int x,y;
public Rect(int x, int y) {
// 자기자신을 호출할때 사용
this.x = x;
this.y = y;
}
}
super() : 자신이 상속받은 부모의 생성자를 호출하는 생성자 메소드
public class Point{
protected int x,y;
public Point(int x,int y) {
this.x =x;
this.y = y;
}
}
public class Rect extends Point{
private int x2,y2;
public Rect(int x, int y) {
// super() 함수로 상위 클래스의 생성자를 호출해준다.
super(x,y);
x2 = x;
y2 = y;
}
}
super : 자신이 상속받은 부모를 가르키는 레퍼런스 변수
public class Point{
protected int x,y;
public Point(int x,int y) {
this.x =x;
this.y = y;
}
}
public class Rect extends Point{
private int x2,y2;
public Rect(int x, int y) {
// super() 함수로 상위 클래스의 생성자를 호출해준다.
super(x,y);
x2 = x;
y2 = y;
// super를 통해서 상위 클래스 변수 호출가능
System.out.println(super.x);
}
}