Back-End/Java

[자바 / Java] 생성자(constructor)

Kangharyeom 2022. 9. 5. 15:47
728x90

생성자는 객체를 생성하는 역할을 하는 클래스의 구성요소다.

또한 생성자는 인스턴스 변수들을 초기화하는데 사용되는 특수한 메서드다.

 

생성자와 메서든 다음과 같은 차이점이 있다. 

  • 생성자의 이름은 반드시 클래스 이름과 같아야 한다.
  • 생성자는 리턴 타입이 없다.

 

 

예시를 보며 이해하자.

public class ConstructorExample {
    public static void main(String[] args) {
        Constructor constructor1 = new Constructor(); // 인스턴스 생성, 인스턴스 변수 초기화
        Constructor constructor2 = new Constructor("This is an Example");
        Constructor constructor3 = new Constructor(15,34);
    }
}

class Constructor { // 생성자의 기본 구조 
    Constructor() { // 생성자 오버로딩
        System.out.println("1번 생성자");
    }

    Constructor(String str) { // (2) 
        System.out.println("2번 생성자");
    }

    Constructor(int a, int b) { // (3) 
        System.out.println("3번 생성자");
    }
}

만약 생성자가 클래스 안에 포함되어 있지 않다면 어떻게 될까?

이런 경우에는 자바 컴파일러가 기본 생성자(=매개변수가 없는 생성자)를 자동으로 추가해준다. 

 

매개변수가 있는 생성자는 매서드처럼 호출시에 매개변수를 통해 값을 받아 인스턴스를 초기화 한다.

 

this vs this()
  • this()
    • 자신이 속한 클래스에서 다른 생성자를 호출하는 경우
    • 메서드는 반드시 생성자의 내부에섬만 사용할 수 있다.
    • 메서드는 반드시 생성자의 첫 줄에 위치해야 한다.

코드와 함께 이해하자

ublic class ThisMethodTest {
    public static void main(String[] args) {
        ThisExam default = new ThisExam();
        ThisExam thisMethod = new ThisExam(7);
    }
}

class ThisExam  {	
    public ThisExam() {		// 
        System.out.println("ThisExam의 기본 생성자 호출!");  ---------1 ----------3
    };

    public ThisExam(int x) { 
        this(); --------2
        System.out.println("ThisExam의 두 번째 생성자 호출!"); ------------4
    }
}

ThisExam에서 첫 번째 생성자가 호출되고 (1)---"ThisExam의 기본 생성자 호출!"이 출력된다.

 

다음 두 번째 생성자가 호출되고 (2)---this()를 실행한다. this()는 첫 번째 생성자를 호출하고

"ThisExam의 기본 생성자 호출!"이 출력된다.

 

마지막으로  "ThisExam의 두 번째 생성자 호출!"이 출력된다.

 

 

 

  • this 키워드
    • 인스턴스 변수와 생성자의 매개변수 이름이 같은 경우 이를 구분하기 위한 용도로 사용되는 방법이 this 키워드다.
    • this는 인스턴스 자신을 가리킨다. 참조변수가 인스턴스 멤버에 접근 할 수 있도록 하는 것과 같이, this를 통해 인스턴스 자신의 변수에 접근할 수 있다.
    • this키워드는 주로 인스턴스의 필드명과 지역변수를 구분하기 위한 용도로 사용된다.