Programming/Java

[Java] 생성자와 this / super

kmindev 2023. 10. 13. 17:58

남궁성님의 Java의 정석(3rd Edition)을 보고 정리한 글입니다.

 

this와 super를 알아보기 전에 생성자에 대해서 알아보자.

 

1. 생성자(Constructor)란?

  • 인스턴스가 생성될 때 호출되는 메서드(인스턴스 초기화 메서드)
  • 인스턴스 변수 초기화 또는 인스턴스생성시 수행할 작업에 사용
  • 모든 클래스는 하나 이상의   생성자가 있어야 한다.
  • 생성자 이름은 클래스 이름과 같다.
  • 생성자는 리턴값이 없다.(void는 쓰지 않음)
접근제한자 클래스이름(매개변수) {
	// 수행될 코드(인스턴스 변수 초기화 등)
}

 

2. 생성자의 종류

기본 생성자

  • 매개변수가 없는 생성자
  • 생성자가하나도 없으면 컴파일러가 기본 생성자를 추가한다
class Data {
	int value;

	Data() { } // 기본 생성자(생성자가 하나도 없으면 생략해도 컴파일 시 추가된다.)
}

 

매개변수가 있는 생성

  • 기본 생성자가 아닌 매개변수가 있는 생성자를 뜻한다.
class Data {
	int value;

	Data(int value) { // 매개변수가 있는 생성자
		this.value = value;
	}
}

 

 

3. this, this(), this(매개변수)

 

a. this ?


this는 인스턴스의 주소를 저장하고 있는 자신을 가르키는 참조변수로 인스턴스 멤버를 지정할 때 사용한다.

public class Car {
	String color;
	int weight;
	int door;

	Car(String color, int weight) {
		this.color = color;
		this.weight = weight;

		this.setDoor(weight);
	}

	void setDoor(int door) {
		this.door = door;
	}
}

 

 

b. this(), this(매개변수) ?


this(), this(매개변수)는 같은 클래스의 다른 생성자를 호출할 때 사용한다.

생성자 내부에서만 사용할 수 있으며, 다른생성자를 호출할 때는 반드시 첫 번째 문장에 와야한다.   

public class Car {
	Car() {
		System.out.println("this1");
	}

	Car(int weight) {
		this();
		System.out.println("this2");
	}

	Car(String color, int weight) {
		this(3);
//		this();   // 생성자를 호출할 때는 반드시 첫번째 실행 문장에서 호출해야 한다.
		System.out.print("this3");
	}
}

public class Class1 {
	public static void main(String args[]) {
		Car car = new Car("white", 3);
	}
}

실행결과
this1
this2
this3

 

 

4. super, super(), super(매개변수)

 

a. super ?


부모의 멤버와 자신의 멤보를 구별하는 데 사용하는 참조변수

class Parent {
    int x = 10;
}

class Child extends Parent{
    int x = 20;

    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

 

 

 

b. super(), super(매개변수) ?


  • 자식클래스의 인스턴스를 생성하면, 자식의 멤버와 부모의 멤버가 하벼진 하나의 인스턴스가 생성된다.
  • 부모드 멤버들도 초기화가 필요하기 때문에 자식의 생성자의 첫 문장에는 부모의 생성자를 호출해야 한다.
  • Object 클래스를 제외한 모든 클래스의 생성자 첫 줄에는 같은 클래스의 다른 생성자 또는 부모의 생성자를 호출해야 한다.(생략시 super() 자동 삽입)   
class Point extends Object { // extends Object 생략시 자동 삽입
    int x;
    int y;
    
    Point() {
        this(0, 0);
    }

    Point(int x, int y) {
    	// super() 생략시 Object 클래스의 생성자를 호출한다.
        this.x = x;
        this.y = y;
    }
}