본문 바로가기

Java

This / This()와 Super / Super()

[ This / This() ] 

public class thisEx {
	
	int value = 100;
	
	public thisEx(int value) {
		System.out.println(value);
	}
	
	public static void main(String[] args) {
		thisEx ex = new thisEx(2);
	}
}

위 코드에서 클래스 영역의 value를 100으로 주고 thisEx를 객체화 하며 2라는 파라미터를 넣어줬다.

이때 생성자는 2를 value로 받아서 사용하기때문에 콘솔엔 2가 나온다.

 

 

public class thisEx {
	
	int value = 100;
	
	public thisEx(int value) {
		System.out.println(this.value);
	}
	
	public static void main(String[] args) {
		thisEx ex = new thisEx(2);
	}
}

하지만 같은 코드에 this. 를 붙이기만 했는데 콘솔에는 100이 찍힌다.

 

이것이 this를 쓰는 이유이다. 

 

동일한 이름의 변수가 사용될 경우 클래스 영역에서 정의한 변수를 식별할 수 있도록 하기위해!

 

 

또한, this와 this()는 다르다.

 

this가 변수를 식별하기 위해서라면 this()는 클래스 영역의 생성자를 불러올때 쓰는 것이다.

 

[ Super / Super() ] 

class Parent {
	int value = 100;
}

class Child extends Parent {
	int value = 2;
    
	void display() {

		System.out.println(value);

		System.out.println(this.value);

		System.out.println(super.value);

	}

}

public class superEx {

	public static void main(String[] args) {

		Child c = new Child();

		c.display();

	}

}

Parent클래스와 그를 상속받는 Child클래스를 생성하고 value / this.value / super.value 를 각각 찍어봅니다.

 

지역변수인 value와 this 참조변수인 this.value의 값은 Child클래스 영역 내의 값인 2가 찍힙니다. 

 

하지만 super.value의 값은 100이 나옵니다 왜일까요?

 

super 참조 변수는 부모 클래스의 변수를 가져옵니다. 

 

이처럼 super는 부모 클래스의 멤버에 접근하기 위해 사용됩니다.

 

마찬가지로 super와 super()는 다른데요.

 

this() 메소드가 같은 클래스의 다른 생성자를 호출할 때 사용된다면,

 

super() 메소드는 부모 클래스의 생성자를 호출할 때 사용됩니다.

 

 

728x90
반응형