생성자 메서드
Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 87개 중 7번째.
생성자(constructor)는 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";
}
}constructor는 객체의 상태를 초기화합니다
Book book = new Book("1984", "Orwell");
// 생성자가 즉시 실행되고, 필드가 설정됩니다constructor를 작성하지 않으면 Java가 기본 빈 constructor를 제공합니다. 어떤 constructor든 하나 작성하면 기본 constructor는 더 이상 자동으로 제공되지 않습니다.
챌린지
중급Create Book class를 만들고 모든 fields를 초기화하는 constructor를 작성하세요:
privatefields:title,author(String),pages(int)- 세 값을 모두 받으며
this를 사용해 할당하는constructor - 각
field에 대한gettermethod "<title> by <author> (<pages> pages)"를 반환하는getSummary()method
직접 해보기
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 클래스단일 및 다중 레벨 상속다중 클래스 상속이 불가능한 이유요약 - 직원 계층 구조직접 연습해 보세요: 온라인 Java 컴파일러