Java/Grammar

[Java] 생성자 (Constructor)

annovation 2025. 4. 30. 09:30

생성자 (Constructor)

💡생성자란?

  • 객체가 생성될 때 자동으로 호출되어, 객체의 초기 상태를 설정하는 특별한 메서드 [각주:1]
  • 클래스 이름과 동일한 이름을 가져야 하며, 리턴 타입이 없다.
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.

 

✅ 예시

public class User {
    String name;

    // 생성자
    public User(String name) {
        this.name = name;
    }
}

 

💡왜 필요한가?

  • 객체 생성 시 필수값 입력을 강제할 수 있어, 객체 일관성을 보장함

기본 생성자 (Default Constructor)

💡기본 생성자란?

  • 매개변수가 없는 생성자
  • 클래스에 생성자가 하나도 없다면, 컴파일러가 자동으로 생성 [각주:2]
The compiler automatically provides a no-argument, default constructor for any class without constructors.
  • 하지만 생성자가 하나라도 있으면 기본 생성자는 직접 정의해야 함

✅ 예제

public class Book {
    String title;

    // 명시적 생성자 존재 시, 아래 기본 생성자 없으면 컴파일 에러
    public Book(String title) {
        this.title = title;
    }

    public Book() {} // 직접 정의 필요
}

생성자 오버로딩 (Constructor Overloading)

💡생성자 오버로딩이란?

  • 동일 클래스 내에서 매개변수의 개수나 타입이 다른 여러 생성자를 정의
  • 생성자의 다양한 초기화 방식 제공 가능

✅ 예제

public class Person {
    String name;
    int age;

    public Person() {
        this.name = "Unknown";
    }

    public Person(String name) {
        this.name = name;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

this 키워드

💡this 키워드

  • 인스턴스 자신의 참조값 [각주:3]
  • 주로 필드와 지역변수를 구분하거나 메서드 체이닝 시 사용
Within an instance method or a constructor, this is a reference to the current object.


✅ 예제

public class Car {
    String model;

    public Car(String model) {
        this.model = model; // this로 필드 구분
    }
}

 

💡this()

  • 생성자 내부에서 다른 생성자를 호출 [각주:4]
  • 반드시 첫 줄에만 위치해야 함
 you can also use the this keyword to call another constructor in the same class.

 

 

✅ 예제

public class Phone {
    String brand;
    int year;

    public Phone() {
        this("Unknown", 2020); // 다른 생성자 호출
    }

    public Phone(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }
}

출처

반응형