-
자바의 정석 Ex7_2 (this, super)Java/자바의정석 2023. 2. 20. 14:48반응형
package Chap07; class Ex7_2 { public static void main(String args[]) { Child c = new Child(); c.method(); } } class Parent { int x=10; } class Child extends Parent { static { } int x=20; void method() { System.out.println("x=" + x); System.out.println("this.x=" + this.x); System.out.println("super.x="+ super.x); } }
===========실행결과===========
x=20
this.x=20
super.x=10위의 코드를 분석해보자.
class Parent { int x=10; }
우선 Parent클래스의 필드에 iv(인스턴스변수) x의 값에 10이 주어졌다.
class Child extends Parent { static { } int x=20; void method() { System.out.println("x=" + x); System.out.println("this.x=" + this.x); System.out.println("super.x="+ super.x); } }
그리고 그런 Parent클래스를 상속하는 Child 클래스
Child클래스 필드에서 int x= 20; 과 같이 iv(인스턴스 변수)가 선언되어 있다.
그리고 method()에서 this.x , super.x 를 호출한다.
this란?
- 현재 클래스의 인스턴스를 의미합니다.
- 즉, 현재 클래스의 인스턴스변수를 가르킵니다
super란?
- 자식 클래스에서 상속받은 부모 클래스의 멤버변수를 참조할때 사용합니다.
this.x 의 경우 현재 클래스 -> Child 의 인스턴스 -> int x=20;을 의미하게 된다.
super.x의 경우 부모클래스 -> Parent의 멤버변수 -> int x=10;을 의미하게된다.
여기서 만약 자식클래스인 int x =20;이 선언되지 않았는다면
this.x 는 가장 가까운 x의 값을 찾게되며 Parent 의 int x =10;의 값을 찾아가게된다.
하지만 Parent에 x값이 없다면 super.x는 참조할곳이 없어 에러가 발생한다.
반응형'Java > 자바의정석' 카테고리의 다른 글
자바의정석 Ex7_10 추상 클래스, 추상 메서드 (0) 2023.02.21 자바의 정석 Ex7_9 (하나의 배열에 여러종류의 객체 저장) (0) 2023.02.20 자바의정석 Ex7_7(다형성) (0) 2023.02.20 자바의 정석 (this, super)의 이해 (0) 2023.02.20 자바의 정석 Ex7_1 (클래스 초기화, 인스턴스 초기화) (0) 2023.02.20