Java에서는 super, super() 혹은 this, this() 를 자주 볼 수 있다.
this - 현재 클래스의 멤버변수를 지정할 때 사용
public class Ex{
private int weight;
private int height;
public void set(int weight, int height){
this.weight = weight;
this.height = height;
}
}
위 처럼 클래스 안에서 해당 멤버변수에 값을 설정하기 위해 this를 사용하였다. 또한 매개변수와 클래스 내의 멤버변수를 구분하기도한다. (this를 붙이면 클래스 멤버변수, 안붙이면 매개변수)
this() - 현재 클래스 안에 정의된 다른 생성자를 부를 때 사용
public class Ex{
private int weight;
private int height;
public Ex(){
this(1, 1);
}
public Ex(int weight){
this(weight, 1);
}
public Ex(int weight, int height){
this.weight = weight;
this.height = height;
}
}
main()에서 객체를 생성했을 때 생성자 값이 하나만 들어오거나 들어오지 않을 경우 해당 생성자 메소드에서 this()를 사용해 주요 메소드를 호출할 수 있다.
super - 자식 클래스에서 부모 클래스의 멤버변수를 사용
public class Shape{
protected String name;
protected int x;
}
public class Rect extends Shape{
public int y;
public Rect(String name, int x, int y){
super.name = name;
super.x = x;
this.y = y;
}
}
super() - 자식 클래스가 부모 클래스의 생성자를 부를 때 사용
public class Shape{
private String name;
private int x;
public Shape(String name, int x){
this.name = name;
this.x = x;
}
}
public class Rect extends Shape{
public int y;
public Rect(String name, int x, int y){
super(name, x);
this.y = y;
}
}