개인공부/java
생성자
케잉
2024. 6. 3. 21:36
public class Book {
String title;
String author;
int page;
// 코드 완성하기
// 생성자 생성하는 것이 객체 생성하는게 아님 메서드처럼 초기화 로직을 수행하는 것
Book() {
this("", "");
//페이지는 0으로 초기화 되니까 안 씀
}
Book(String title, String author) {
this(title, author, 0);
}
Book(String title, String author, int page) {
this.title = title;
this.author = author;
this.page = page;
}
void displayInfo(){
System.out.println("제목: "+ title + " 저자: "+ author + " 페이지: " + page);
}
}
public class BookMain {
public static void main(String[] args) {
//기본 생성자 사용
Book book1 = new Book();
book1.displayInfo();
//title과 author만을 매개변수로 받는 생성자
Book book2 = new Book("모순", "양귀자");
book2.displayInfo();
//모든 필드를 매개변수로 받는 생성자
Book book3 = new Book("이방인", "알베르 카뮈", 150);
book3.displayInfo();
}
}
생성자 생성하는 것이 객체 생성하는게 아니다.
메서드처럼 초기화 로직을 수행하는 것