생성자 메서드
Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 87개 중 7번째.
생성자는 new를 사용하여 객체를 생성할 때 자동으로 실행되는 특별한 메서드입니다. 클래스와 동일한 이름을 가지며 반환 타입이 없습니다.
기본 생성자
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}기본 생성자 (매개변수 없음)
public class Book {
private String title;
public Book() {
this.title = "Unknown";
}
}생성자는 객체의 상태를 초기화합니다
Book book = new Book("1984", "Orwell");
// 생성자가 즉시 실행되고 필드가 설정됩니다생성자를 작성하지 않으면 Java는 기본 빈 생성자를 제공합니다. 어떤 생성자라도 작성하면 기본 생성자는 더 이상 자동으로 제공되지 않습니다.
챌린지
중급모든 필드를 초기화하는 생성자를 가진 Book 클래스를 생성하세요:
- Private 필드:
title,author(String),pages(int) - 세 개의 값을 모두 받아
this를 사용하여 할당하는 생성자 - 각 필드에 대한 Getter 메서드
"<title> by <author> (<pages> pages)"를 반환하는getSummary()메서드
치트 시트
생성자는 new를 사용하여 객체를 생성할 때 자동으로 실행되는 특별한 메서드입니다. 클래스와 이름이 같으며 반환 타입이 없습니다.
기본 생성자:
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}기본 생성자 (매개변수 없음):
public class Book {
private String title;
public Book() {
this.title = "Unknown";
}
}생성자를 사용하여 객체 생성하기:
Book book = new Book("1984", "Orwell");
// 생성자가 즉시 실행되어 필드가 설정됩니다생성자를 직접 작성하지 않으면 Java에서 기본 빈 생성자를 제공합니다. 생성자를 하나라도 작성하면 기본 생성자는 더 이상 자동으로 제공되지 않습니다.
직접 해보기
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String title = scanner.nextLine();
String author = scanner.nextLine();
int pages = Integer.parseInt(scanner.nextLine());
Book book = new Book(title, author, pages);
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Pages: " + book.getPages());
System.out.println(book.getSummary());
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
4상속
상속의 기초 (extends)super 키워드메서드 오버라이딩 (@Override)생성자 체이닝Object 클래스단일 및 다중 레벨 상속다중 클래스 상속이 불가능한 이유요약 - 직원 계층 구조