「 정의 」
- this : 자기 객체를 가리키는 참조 변수명으로, 메서드 내에서 멤버 변수(인스턴스 변수, 클래스 변수)와 지역변수(메서드 안에서 정의된 변수)의 이름이 같을 때 구분하기 위한 용도로 사용되며 생략 시 컴파일러가 자동으로 추가해준다.
- this() : 생성자 함수 내에서 같은 클래스에 있는 다른 생성자를 호출할 때 사용되며 항상 생성자 내에서 첫 줄에 위치한다.
- super : 상위 클래스 객체의 멤버 값(변수 또는 메서드)을 참고한다.
- super() : 하위 클래스의 생성자 내에서 상위 클래스의 생성자를 호출할 때 사용, 항상 생성자 내에서 첫 줄에 위치한다.
「 두 개의 같은 이름의 변수를 구별 : this VS super 」
public class Example {
public static void main(String[] args) {
Child child = new Child();
child.aboutNumber();
}
}
class Parent {
int number = 10;
}
class Child extends Parent {
int number = 5;
void aboutNumber () {
System.out.println(number); // 5
System.out.println(this.number); // 5
System.out.println(super.number); // 10
}
}
「 this() VS super() 」
public class Example2 {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
child.hello();
}
}
class Parent {
String name;
int age;
Parent() { // 기본 생성자
this("김아지", 36); // 매개변수가 있는 생성자 호출
System.out.println("부모 클래스의 기본 생성자 호출");
System.out.println("Parent 이름 : " + name + "\nParent 나이 : " + age);
System.out.println("--------------------------");
}
Parent(String name, int age) { // 매개변수가 있는 생성자
this.name = name;
this.age = age;
}
void hello() {
System.out.println("부모 클래스의 hello 메서드 호출");
}
}
class Child extends Parent {
Child() {
super("삐삐", 32);
System.out.println("자식 클래스 생성자 호출");
System.out.println("Child 이름 : " + name + "\nChild 나이 : " + age);
System.out.println("--------------------------");
}
@Override
void hello() {
super.hello(); // Parent 클래스의 hello 메서드 호출
}
}
♣ 위 코드의 출력 값

'언어(Language) > [자바] 객체지향 프로그래밍 심화' 카테고리의 다른 글
커피 주문하기 (1) | 2023.05.10 |
---|