1.생성자
1. 생성자 선언 및 사용
- 객체를 생성할 떄 new다음에 오는 것을 생성자라고 한다.
public Pen(String init_color, int init_price) {
color = init_color;
price = init_price;
System.out.println("생성자를 이용하여 color, price를 초기화");
}
public class PenConstructorExample {
public static void main(String[] args) {
Pen blackPen = new Pen(); // 에러
blackPen.write(1); // 에러
Pen redPen = new Pen("빨간", 900);
redPen.write(2);
}
}
1.1 기본 생성자
- 인자가 없고 클래스 이름과 동일할떄 → 기본생성자의 이름은 클래스의 이름과 동일하다.
public pen() {}
1.2 생성자 중복
- 하나의 클래스에 생성자를 여러개 선언해 두는 것을 생성자 중복이라고 한다.
- 중복해서 정의하는 이유는 여러가지 상황에서 객체를 생성하는 유연성을 제공하기 위함이다.
- this는 현재 객체의 멤버(변수 또는 메서드)를 참조하기 위해 사용한다.
public class Book {
String title;
String author;
int pageCount;
// 기본 생성자
public Book() {
// 모두 기본값 설정
this.title = "Unknown Title";
this.author = "Unknown Author";
this.pageCount = 0;
}
// 일부 정보만 받는 생성자
public Book(String title, String author) {
this.title = title;
this.author = author;
this.pageCount = 0; // 나머지는 기본값으로 초기화
}
// 모든 정보를 받는 생성자
public Book(String title, String author, int pageCount) {
this.title = title;
this.author = author;
this.pageCount = pageCount;
}
}