참조변수 Super

AnHyunDong·2022년 9월 26일
0

Java

목록 보기
2/4

참조변수 super(=this)

  • 객체 자신을 가르키는 참조변수
  • 인스턴스 메서드(생성자)내에서만 존재
  • 조상의 멤버를 자신의 멤버와 구별할 때 사용됨
  • 조상에게는 super, 자식에게는 this를 붙임

코드

class Ex7_2 {
	public static void main(String args[]) {
    	Child c = new Child();
        c.method()[
    }
}

class Parent { int x = 10; /* super */ } //1st 멤버

class Child extend Parent {
	int x = 20; //2nd 멤버
    
    void method() {  //3rd 멤버
    System.out.println("x=" + x); // 20
    System.out.println("x=" + this.x); // 20
    System.out.println("x=" + super.x); // 10
  • 3개의 멤버를 지니고 있음
    • 조상의 x
    • 자식의 x
    • 자식의 method
  • super.x != this.x(서로 다름)

코드2

class Ex7_3 {
	public static void main(String args[]) {
    	Child2 c = new Child2();
        c.method()[
    }
}

class Parent2 { int x = 10; /* super.x와 this.x 둘 다 가능함 */ }

class Child2 extend Parent2 {
    void method() {
    System.out.println("x=" + x); // 10
    System.out.println("x=" + this.x); // 10
    System.out.println("x=" + super.x); // 10
  • 2개의 멤버를 가지고 있음
    • 부모의 x
    • 자식의 method
  • super.x = this.x(서로 같음)

super() - 조상의 생성자

  • 조상의 생성자를 호출할 때 사용됨
    • 생성자(초기화 블럭)은 상속이 안됨
  • 조상의 멤버는 조상의 생성자를 호출해서 초기화
  • 생성자의 첫 줄에 반드시 생성자를 호출해야 됨 > 그렇지 않으면 컴파일러가 생성자의 첫 줄에 super();를 삽입함(중요)
class Point {
	int x, y;
    
    Point(int x, int y) {
    	this.x = x;
        this.y = y;
    }
}

class Point3D extends Point {
	int z;
    
    class Point3D(int x, int y, int z {
    	super(x, y); //조상클래스의 생성자 Point(int x, int y)를 호출
        this.z = z; //자신(자식)의 멤버를 초기화
    }
}

예제

package hello;

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; 
	}
}

public class Super {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

결과

  • 컴파일러 에러
    • 자식 생성자에서 부모 생성자를 this로 정의했기 때문에

예제2

package hello;

class Point {
	int x;
	int y;
	
	Point(int x, int y) {
		super(); //Object();
		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) {
		super(x,y); //Point() 호출
		this.z = z;
	}
	
	 String getLocation() { //오버라이딩
		return "x:" + x + ", y:" + y + ", z:" + z; 
	}
}

public class Super {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Point3D p3 = new Point3D(1,2,3);
		System.out.println(p3); //public toString 인 경우에만 이렇게 사용이 가능함
		System.out.println(p3.getLocation());
	}

}

결과2

  • 모든 생성자는 첫줄에 다른 생성자를 호출해야 됨 > super();

profile
사진은 남아 추억이 메모는 남아 스펙이 된다

0개의 댓글