Java 참조변수 super
참조변수 super
- 참조변수 this와 유사하다. (this : lv, iv 구별할 때 쓰임)
- 객체 자신을 가리키는 참조변수. 인스턴스 메서드(생성자)내에만 존재
- 조상의 멤버를 자신의 멤버와 구별할 때 사용
public class EX7_3 {
public static void main(String[] args) {
Child child = new Child();
child.method();
}
}
class Parent{
int x = 10; // super
}
class Child extends Parent{
int x = 20; // this
void method(){
System.out.println("x= " + x); // x= 20
System.out.println("this.x= " + this.x); // this.x= 20
System.out.println("super.x= " + super.x); // super.x= 10
}
}
super() : 조상의 생성자
- this()와 유사함
- 조상의 생성자를 호출할 때 사용
- 조상의 멤버는 조상의 생성자를 호출해서 초기화
class MyPoint{
int x, y;
MyPoint(int x, int y){
this.x = x;
this.y = y;
}
}
class MyPoint3D extends MyPoint{
int z;
MyPoint3D(int x, int y, int z){
this.x = x; // 조상의 멤버를 초기화
this.y = y; // 조상의 멤버를 초기화
this.z = z;
}
// There is no default constructor available in 'MyPoint'
// 조상의 멤버는 super()로 초기화 해주는게 맞다.
}
- 올바르게 바꾼 모습(
super()
를 적용한 모습)
class MyPoint{
int x, y;
MyPoint(int x, int y){
this.x = x;
this.y = y;
}
}
class MyPoint3D extends MyPoint{
int z;
MyPoint3D(int x, int y, int z){
super(x, y); // MyPoint(x, y)와 같은 의미
// this.x = x; // 조상의 멤버를 초기화
// this.y = y; // 조상의 멤버를 초기화
this.z = z;
}
// There is no default constructor available in 'MyPoint'
// 조상의 멤버는 super()로 초기화 해주는게 맞다.
}
- 생성자의 첫 줄에 반드시 생성자를 호출해야 한다. 그렇지 않으면 컴파일러가 생성자의 첫 줄에
super();
를 삽입한다.
public class EX7_3 {
public static void main(String[] args) {
Child child = new Child();
child.method();
}
}
class Parent{
int x = 10; // super
}
class Child extends Parent{
int x = 20; // this
void method(){
System.out.println("x= " + x); // x= 20
System.out.println("this.x= " + this.x); // this.x= 20
System.out.println("super.x= " + super.x); // super.x= 10
}
}
class MyPoint{
int x, y;
MyPoint(int x, int y){
this.x = x;
this.y = y;
}
}
class MyPoint3D extends MyPoint{
int z;
MyPoint3D(int x, int y, int z){
this.x = x; // 조상의 멤버를 초기화
this.y = y; // 조상의 멤버를 초기화
this.z = z;
}
// There is no default constructor available in 'MyPoint'
// 조상의 멤버는 super()로 초기화 해주는게 맞다.
}
super()
를 적용한 모습)class MyPoint{
int x, y;
MyPoint(int x, int y){
this.x = x;
this.y = y;
}
}
class MyPoint3D extends MyPoint{
int z;
MyPoint3D(int x, int y, int z){
super(x, y); // MyPoint(x, y)와 같은 의미
// this.x = x; // 조상의 멤버를 초기화
// this.y = y; // 조상의 멤버를 초기화
this.z = z;
}
// There is no default constructor available in 'MyPoint'
// 조상의 멤버는 super()로 초기화 해주는게 맞다.
}
super();
를 삽입한다.Author And Source
이 문제에 관하여(Java 참조변수 super), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@nathan29849/Java-참조변수-super저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)