this와 super는 각각 객체 자신과 부모 객체를 참조하는 데 사용됨
이를 통해 클래스의 상속 관계에서 유용하게 활용할 수 있음
this 키워드
▷ 현재 객체 자신을 참조하는 키워드
- 인스턴스 변수와 로컬 변수의 이름이 동일할 때 이를 구분하기 위해 사용
- 현재 객체의 다른 메서드를 호출하기 위해 사용
- 현재 클래스의 다른 생성자를 호출하기 위해 사용 (생성자 체이닝)
super 키워드
▷ 부모 클래스의 멤버(변수나 메서드)를 참조하는 키워드
- 부모 클래스의 멤버 변수와 자식 클래스의 멤버 변수의 이름이 동일할 때 이를 구분하기 위해 사용
- 부모 클래스의 메서드를 호출하기 위해 사용
- 부모 클래스의 생성자를 호출하기 위해 사용
// 부모 클래스
class Parent {
String name;
// 부모 클래스의 생성자
public Parent(String name) {
this.name = name;
}
// 부모 클래스의 메서드
public void display() {
System.out.println("Parent name: " + name);
}
}
// 자식 클래스
class Child extends Parent {
String name;
// 자식 클래스의 생성자
public Child(String childName, String parentName) {
super(parentName); // 부모 클래스의 생성자 호출
this.name = childName; // 현재 객체의 name 변수 초기화
}
// 자식 클래스의 메서드
public void display() {
super.display(); // 부모 클래스의 display 메서드 호출
System.out.println("Child name: " + this.name); // 현재 객체의 name 변수 출력
}
}
// 메인 클래스
public class Main {
public static void main(String[] args) {
Child child = new Child("John", "Michael");
child.display();
}
}
// Parent name: Michael
// Child name: John
▷ this 키워드 사용
- this.name = childName;
- this 키워드는 현재 객체의 name 변수를 참조
- 로컬 변수 childName을 현재 객체의 인스턴스 변수 name에 할당
- System.out.println("Child name: " + this.name);
- this 키워드는 현재 객체의 name 변수를 참조하여 출력
▷ super 키워드 사용
- super(parentName);
- super 키워드는 부모 클래스의 생성자를 호출
- parentName 값을 부모 클래스의 name 변수에 초기화
- super.display();
- super 키워드는 부모 클래스의 display 메서드를 호출
- 부모 클래스의 name 변수를 출력
'Language > Studying' 카테고리의 다른 글
[Java] Java API (0) | 2024.07.17 |
---|---|
[Java] Heap 영역과 Stack 영역 (feat. 동적할당, 정적할당) (0) | 2024.07.16 |
[Java] ArrayList와 HashMap (0) | 2024.07.08 |
[Java] 상속(Inheritance) (0) | 2024.07.03 |
## 코딩테스트 연습문제 (0) | 2023.08.09 |