생성자 (Constructor)
💡생성자란?
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)
💡기본 생성자란?
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 키워드
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()
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;
}
}
출처
반응형
'Java > Grammar' 카테고리의 다른 글
[Java] 클래스(Class), 객체(Object), 인스턴스(Instance) (0) | 2025.04.27 |
---|---|
[Java] 배열 (Arrays) (1) | 2025.04.25 |
[Java] 변수의 생존 범위 (Scope) (1) | 2025.04.24 |
[Java] 제어 흐름 문 (Control Flow Statements) (2) | 2025.04.22 |
[Java] Checked, Unchecked Exception (0) | 2025.03.25 |