자바의 정석 - 기초편

참조변수 super, 생성자 super()

ODaram 2022. 8. 22. 17:35

▶참조변수 super

 ( ≒ this. lv와 iv구별에 사용)

  - 객체 자신을 가리키는 참조변수. 인스턴스 메서드(생성자)내에만 존재 (= static 메서드내에 사용불가)

  - 조상의 멤버를 자신의 멤버와 구별할 때 사용

class Ex7_2 {
   puvlic static void main (String args[]) {
         Chihld c= new Child();
         c.method();
    }
}
class Parent (int x = 10; /* super.x */ }
class Child extends Parent {
  int x = 20;     // this.x
  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_Ex7_3 {
  public static void main (strig args[]) {
     Child2 c = new Child2();
     c.method();     
  }
}
class Parent2 { int x = 10;  /* super.x 와 this.x 둘 다 가능 */ }
class Child2 extends Parent2 {
  void method() {
    System.out.println("x=" + x);
    System.out.println("this.x =" + this.x);
    System.out.println("super.x=" + super.x);
  }
}

 

 

▶super() - 조상의 생성자

  - 조상의 생성자를 호출할 때 사용  (생성자. 초기화 블럭 - 상속 X)

 - 조상의 멤버는 조상의 생성자를 호출해서 초기화

 - 생성자의 첫 줄에 반드시 생성자를 호출해야 한다.  ( super() or this() )

    그렇지 않으면 컴퍼일러가 생성자의 첫 줄에 super();를 삽입

class Point {
   int x;
   int y;
   
  Point () {
        this (0,0);        // 첫 줄에 생성자 호출 조건 만족
   }
  Point (int x, int y) {
        this.x = x;        // 첫 줄 생성자 호출 X   => 컴파일러가 윗줄에 super(); <조상의 기본생성자> 코드 넣음
        this.y = y;
   }
}
위 코드 컴파일 하면 super() 생성자 생김
Point (int x, int y) {
       super ();       // object();      // 첫 줄에 생성자 호출 조건 만족
        this.x = x;
        this.y = y;
}

 


suepr() - 조상의 생성자 예제)

class Point {
  int x;
  int y;

 Point (int x, int y) {
     this.x = x;                  ->      super();      // object(),   컴파일러 자동 추가
     this.y = 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;                                                                   ->   super();    // object()       컴파일러 자동 추가
     this.y = y;                                                                   ->   this.x = x;
     this.z = z;                                                                   ->   this.y = y  
                                                                                        ->  this.z = z;
  }                                                                                  
  string getLocation() {      // 오버라이딩
     return "x :" + x + ", y :" + y + " , z :" + z;
  }
}

'자바의 정석 - 기초편' 카테고리의 다른 글

import문 /static import문  (0) 2022.08.23
패키지, 클래스 패스  (0) 2022.08.23
오버라이딩  (0) 2022.08.17
단일상속, Object클래스  (0) 2022.08.17
클래스 간의 관계, 상속과 포함  (0) 2022.08.16