컨스트럭터(Constructors)
도입됨
7:20
클래스 생성
여기에는 이름, 학년, 등급이라는 세 개의 독립된 변수로 저장된 한 학생이 있습니다. 이것은 작동합니다. 이제 학생 천 명을 추가하십시오. 삼천 개의 변수가 필요합니다…
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| constructor/kənˈstrʌktə/ | A special operation used to initialise a newly created object. |
| default constructor/dɪˈfɒlt kənˈstrʌktə/ | 기본 constructor |
| Parameters/pəˈræmɪtəz/ | |
| overloading/ˌəʊvəˈləʊdɪŋ/ | Declaring methods or constructors with the same name but different parameter lists, so the applicable version is selected from the call. |
이 카드는 새로 추가되어 번역이 준비될 때까지 영어로 표시됩니다.
A parameterised constructor does not supply a no-arg one
- Student declares only Student(String n). Creating new Student("Ada") works, but new Student() has no matching constructor.
- Java supplies an implicit default constructor 默认构造函数 only when none is declared. To allow both calls, explicitly write Student() and Student(String n).

새로운 객체를 설정하는 방법
- A constructor는 object가 생성될 때
new로 실행되어 초기 상태를 설정합니다. class와 동일한 이름을 가지며 반환 유형이 없습니다(void도 포함하여). public Student(String n) { name = n; score = 0; }그 역할: 새 객체에 합리적인 시작 값을 부여하는 것입니다.
Constructor parameters
- 파라미터는 각 새 객체가 자체 값으로 시작하게 합니다.
new Student("Ada")은"Ada"을 생성자의n파라미터에 전달합니다. - 내부에서,
name = n;는 인수를 instance variable에 복사합니다. 각 성공적인new표현식은 동일한 인수를 가져오더라도 별개의 객체를 생성합니다. 다른 인수들이 constructor에 의해 무시되거나 정렬될 경우, 반드시 다른 필드 값을 생성하지는 않을 수 있습니다.
new Student("Ada") 두 번의 실행은 인자가 동일하기 때문에 같은 객체를 가리킵니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
각 성공적인 new 표현식은 별개의 객체를 생성합니다; 인자가 같다고 해서 참조가 같아지는 것은 아닙니다.
Overloading constructors
- A class는 서로 다른 parameter lists를 가진 여러 constructors를 가질 수 있습니다 — overloading.
Student(String n)와Student(String n, int s)는 모두 유효합니다. - Java는 your
newarguments와 일치하는 one을 선택합니다. 이는 caller에게 객체를 구축하는 유연한 방법을 제공합니다.
컨스트럭터는 시작 상태를 설정합니다.
새로운 객체마다 컨스트럭터의 인자에 의해 구성됩니다.
컨스트럭터는 ...을 가집니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
클래스와 동일한 이름, 반환 타입 없음 — void조차도 아님.
언제 컨스트럭터가 실행되나요?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
new는 컨스트럭터를 호출하여 객체를 만듭니다.
컨스트럭터를 직접 작성하지 않으면 Java는 기본 무인자(constructor)를 제공합니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
하지만 어떤 컨스트럭터라도 작성하면 그 무료 기본值是 사라집니다.
매개변수가 있는 컨스트럭터를 정의한 후에도 new Student()는 여전히 자동으로 작동합니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
무료 기본값은 사라졌습니다. 필요하면 무인자 컨스트럭터를 명시해야 합니다.
다른 매개변수 목록을 가진 두 개의 컨스트럭터를 작성하는 것은 ...의 예입니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
동일한 이름, 다른 매개변수 = 오버로딩(overloading).
The default constructor
- A constructor을 아무것도 쓰지 않으면, Java는 parameters가 없는 숨겨진 default constructor를 제공합니다. fields는 먼저 default values(
0,false,null)를 가지며, 이후 명시적 field initializers가 다른 초기 값을 설정할 수 있습니다. - 그러나 어떤 constructor를 작성하면, 그 무료 default는 사라집니다. 따라서 무-arg constructor 및 parameterized one이 필요하면, 두 개를 모두 작성하십시오.
A constructor has the class's name and NO return type — writing void makes it an ordinary method, not a constructor. And once you define any constructor, Java stops giving you the free no-argument default; if you still want new Student(), you must write that constructor yourself.
Order the steps used to evaluate new Student("Ada").
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
The supplied argument selects a matching constructor; declaring it does not also create a no-argument constructor.
Counter에는 private int value = 7;가 있고, 이후 value = 9;를 할당하는 명시적 생성자가 있습니다. 생성 직후 value의 값은 무엇입니까?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
필드 초기화자는 컨스트럭터 본체가 9을 할당하기 전에 7에 값을 부여합니다.
Two constructors for Student:
public Student(String n) { name = n; score = 0; }public Student(String n, int s) { name = n; score = s; }new Student("Ada")→ score0;new Student("Bo", 75)→ score75.
추론을 새로운 사례로 확장하기
- 명시적인 생성자가
value = 9;을 할당하는 이와 동일한 클래스와class Counter { private int value = 7; }를 비교하십시오. 첫 번째는 필드 초기화기 이후 7로 시작하고, 두 번째는 9에서 생성을 끝냅니다. - fields는 field initializers와 constructor body가 실행되기 전에 default 값을 받습니다. programmer가 쓴 무-argument constructor는 compiler가 제공하는 default constructor와 다르지만, 둘 다 arguments를 취하지는 않습니다.
A constructor (same name as the class, no return type) runs on new to set an object's initial state, using parameters for per-object values. A class can overload several constructors. Write no constructor and Java supplies a default no-arg one — but defining any constructor removes that free default.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.