생성

생성자 에서 Java

16개의 연습 문제

생성자 소개

_클래스_의 인스턴스를 만들려면 new 연산자로 생성자를 호출해요. 생성자는 새로 만들어진 인스턴스를 초기화하는 것이 목표인 특별한 종류의 메서드예요. 생성자는 일반 메서드와 비슷하게 생겼지만, 반환 타입이 없고 이름이 클래스 이름과 같아요.

class Library {
    private int books;

    public Library() {
        this.books = 10;
    }
}

// This will call the constructor
var library = new Library();

일반 메서드와 마찬가지로 생성자도 매개변수를 가질 수 있어요. 생성자의 매개변수는 보통 나중에 접근할 수 있도록 (private) 필드에 저장하거나, 한 번만 필요한 계산에 사용해요. 인자는 일반 메서드에 인자를 넘기듯이 생성자에도 넘길 수 있어요.

class Building {
    private int numberOfStories;
    private int totalHeight;

    public Building(int numberOfStories, double storyHeight) {
        this.numberOfStories = numberOfStories;
        this.totalHeight = numberOfStories * storyHeight;
    }
}

// Call a constructor with two arguments
var largeBuilding = new Building(55, 6.2)

생성자를 직접 지정하는 것은 선택 사항이에요. 생성자를 지정하지 않으면 컴파일러가 매개변수가 없는 생성자를 만들어 줘요:

class Elevator {
}

// This will call the (empty) generated constructor
var elevator = new Elevator();

필드에 초기값이 할당되어 있으면, 컴파일러는 그 할당이 실제로는 생성자 안에서 이루어지는 코드를 만들어요. 따라서 다음 두 클래스 선언은 (기능적으로) 동일해요:

class UsingFieldInitialization {
    private int players = 5;
}

class UsingConstructorInitialization {
    private int players;

    public UsingConstructorInitialization() {
        players = 5;
    }
}
GitHub에서 편집 링크가 새 창이나 탭에서 열려요

생성자 배우기