(1) this
1) 정의
<1> 자신의 '객체' or '생성자'를 가리키는 '대명사'
2) Case
<1> 지역변수와 이름이 같은 멤버변수를 해당 지역에서 접근할 때
<2> 자신의 객체를 다른 클래스에게 넘길 때
<3> 자신의 생성자를 호출할 때
ex) class B {
int age;
B() {
this(20); //(3)
}
B(int age) {
this.age = age; //(1)
new BUser(this).use(); //(2)
}
void m() {
System.out.println("m의 age " + age);
}
public static void main(String[] args) {
new B();
}
}
class BUser {
B b;
BUser(B b) {
this.b = b;
}
void use() {
System.out.println("b.age: " + b.age); //멤버
b.m(); //메소드
}
}
(2) super
1) 정의
<1> 부모의 '객체' or '생성자'를 가리키는 '대명사'
2) Case
<1> 부모의 생성자를 호출할 때
<2> 오버라이딩되기전의 부모메소드를 호출할 때
<3> 이름이 동일한 부모의 멤버를 호출할 때
ex) class C {
String name = "홍길동";
C() {
super(); // (1) 모든 객체는 Object 의 자식이므로 extends Object 가 생략되어있다.
}
void m() { //오버라이딩 전
System.out.println("C의 m()");
}
}
class CChild extends C{
String name = "이순신";
CChild(){
super.m(); // (2) 이렇게 호출하면 오버라이딩 전의 메소드 즉, 부모의 메소드를 부를 수 있다.
System.out.println("name: " +super.name); // (3) 호출 되는건 부모의 전역변수 name 이다.
}
void m(){ //오버라이딩 후
System.out.println("CChild의 m()");
}
public static void main(String[] args) {
new CChild();
}
}
'Java > Java' 카테고리의 다른 글
Java 11. 어노테이션 ( Annotation ) (0) | 2022.03.11 |
---|---|
Java 10. 내부클래스 ( Inner Class ) (0) | 2022.03.10 |
Java 08. 제한자( Modifier ) 와 식별자 ( Identifier ) (0) | 2022.03.10 |
Java 07. 예외 처리 (0) | 2022.03.09 |
Java 06. OOP( Object Oriented Programming) 특성 (0) | 2022.03.09 |