생성자와 this, this()

song yuheon·2023년 8월 27일
0

Java

목록 보기
11/46
post-thumbnail

생성자

  • 생성자는 객체 생성 시 호출되며 객체를 초기화한다.

    public Car() {} // 선언
    Car car = new Car(); // 호출
  • 기본 생성자: 매개변수 없는 생성자.

    • 컴파일러는 자동으로 기본 생성자를 추가한다. 해당 클래스의 접근제어자를 따르게 생성된다.
    public class Car {
        public Car() {}
    }
    
    class Car {
        Car() {}
    }
  • 생성자의 주된 역활: 객체 초기화.

    • 필드 초기화나 초기값 대입 가능.
    • 사용자 정의 생성자를 만들 경우, 기본 생성자는 자동으로 제공되지 않는다.
  • 생성자 오버로딩 가능.

    public Car(String modelName) {
        model = modelName;
    }
    
    public Car(String modelName, String colorName) {
        model = modelName;
        color = colorName;
    }
    
    public Car(String modelName, String colorName, double priceValue) {
        model = modelName;
        color = colorName;
        price = priceValue;
    }

this & this()

  • this: 현재 객체 자신을 참조하는 키워드.

    public Car(String model, String color, double price) {
        this.model = model;
        this.color = color;
        this.price = price;
    }
  • return this:

    • 현재 객체의 주소를 반환한다.
    Car returnInstance() {
        return this;
    }
  • this(): 현재 객체의 다른 생성자를 호출하는 키워드.

    • this() 사용 시, 반드시 생성자의 첫 줄에 작성해야 한다.
profile
backend_Devloper

0개의 댓글