본문 바로가기
Java

자바 중급 029. 참조 변수 super 조상클래스 참조변수

by Smart Factory in 2020 2021. 9. 14.
728x90
반응형

안녕하세요. 스마트 팩토리입니다. 

자바 중급 029. 참조 변수 super 조상클래스 참조변수 에 대해 알아보겠습니다. 

 

1. 참조 변수 super

가. 참조 변수 super

-this 와 동일한 기능을 함
-조상멤버와 자신의 멤버를 구분하는 참조변수
- this는 인스턴스 자기 자신의 주소를 가지고 있는 참조변수

나. 참조 변수 super 예시

<< super. java 실행클래스>>

부모클래스와 자식 클래스 모두 동일한 이름의 멤버 변수 이름을 가지고 있을때 

this 와 super에 따라서 값이 명확하게 구분이 됩니다. 

 

부모 클래스에서는 x=10 이고 자식 클래스 에서  x=5입니다. 

객체 생성은 자식 클래스를 활용하여 만들어서 

System.out.println(" x :"+ x); 
자식의 x 값은 5로 나옵니다. 

System.out.println(" this.x :"+ x);
해당 클래스 값 즉 자식 객체가 생성된 영역이므로 x=5

System.out.println(" super.x :"+ super.x);

super는 조상 클래스 영역이므로 x=10이 출력됨.

package ex07_01;
class Parent{
int x=10;
}

class Son5 extends Parent{
int x=5;

void show() { 
System.out.println(" x :"+ x);
System.out.println(" this.x :"+ x);
System.out.println(" super.x :"+ super.x);

}
}

public class Ex08_super {

public static void main(String[] args) {

Son5 s1=new Son5();
s1.show();
        
}

}

 

<< 자식 클래스의 맴버 변수가 없을 때>>

 자식 클래스에 멤버 변수가 없을 때는 부모 클래스에 있는 값을 출력합니다. 

package ex07_01;
class Parent{
int x=10;
}

class Son5 extends Parent{
//int x=5;  --> 주석 처리고 변수가 없는 것과 동일

void show() { 
System.out.println(" x :"+ x);
System.out.println(" this.x :"+ x);
System.out.println(" super.x :"+ super.x);

}
}

public class Ex08_super {

public static void main(String[] args) {

Son5 s1=new Son5();
s1.show();
        
}

}

 

<< 부모클래스에 멤버 변수만 선언된 경우 >>

기본 초기화값인 0으로 되어 출력됩니다. 

여기서  x 값은 모두 부모 클래스 값을 참조하여 출력하게 됩니다. 

 

 

728x90
반응형

댓글