[Java] OOP_참조변수 super와 생성자 super()
참조변수 super와 생성자 super()
*참조변수 super와 생성자 super()를 연관지으면 안된다.
참조변수 super
this와 유사함, (this : lv와 iv 구별에 사용)
객체 자신을 가리키는 참조변수
- 인스턴스 메소드(생성자)내에서만 존재
=> static 메소드에서 사용불가 - 조상 멤버를 자신의 멤버와 구분할 때 사용함
class Ex7-2 {
public static void main(String args[]) {
Child c=new Child();
c.method();
}
}
class Parent {int x=10;} //부모 클래스에 x 1개
class Child extends Parent {
int x=20; // 자식 클래스에 x 1개, 이 x에 this. 붙여줌 => this.x
void method() {
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
}
생성자 super()
조상의 생성자
-
조상의 생성자를 호출할 때 사용함
-
조상의 멤버는 조상의 생성자를 호출하여 초기화
-
생성자의 첫 줄에 반드시 생성자를 호출해야 한다
-> 그렇지 않으면 컴파일러가 생성자의 첫 줄에 super();를 삽입
class Point {
int x;
int y;
Point() {
this(0,0); //자기 자신의 생성자 호출
}
Point(int x, int y) {
super(); //생성자 첫 줄에 없으면 super(); 생성 (=조상의 기본 생성자를 호출하는 것)
this.x=x;
this.y=y;
}
}
예제
class Point {
int x;
int y;
Point(int x, int y) {
this.x=x;
this.y=y;
}
String getLocation() {
return "x :"+x+",y :"+y;
}
}
class Point3D extends Point {
int z;
//에러 고치기
Point3D(int x, int y, int z) {
this.x=x;
this.y=y;
this.z=z;
}
String getLocation() { //오버라이딩
return "x :"+x+",y :"+y+", z :"+z;
}
}
//에러 해결방법
Point3D(int x, int y, int z) {
//1)번 방법 : 조상 Point()를 호출
super();
this.x=x;
this.y=y;
this.z=z;
}
Point3D(int x, int y, int z) {
//2)번 방법 :
//조상의 생성자 Point(int x, int y)를 호출
super(x,y);
this.z=z;
}
Author And Source
이 문제에 관하여([Java] OOP_참조변수 super와 생성자 super()), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jeong11/Java-OOP-참조변수super-생성자super저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)