생성자 오버로딩
Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 87개 중 8번째.
생성자 오버로딩은 서로 다른 매개변수 목록을 가진 여러 개의 생성자를 갖는 것을 의미합니다. 한 생성자에서 다른 생성자를 호출하려면 this()를 사용하세요.
다중 생성자
public class Book {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public Book(String title, String author) {
this.title = title;
this.author = author;
this.pages = 0;
}
}this()를 사용한 생성자 체이닝
public class Book {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public Book(String title, String author) {
this(title, author, 0); // 3개의 매개변수를 가진 생성자를 호출합니다.
}
public Book() {
this("Unknown", "Unknown"); // 2개의 매개변수를 가진 생성자를 호출합니다.
}
}사용법
Book b1 = new Book("1984", "Orwell", 328);
Book b2 = new Book("Dune", "Herbert");
Book b3 = new Book();this()는 생성자 내에서 첫 번째 문장이어야 합니다. 체이닝(Chaining)은 여러 생성자 간의 할당 로직 중복을 방지합니다.
챌린지
중급생성자 체이닝(constructor chaining)을 사용하여 Product 클래스에 대해 세 개의 오버로딩된 생성자를 만드세요:
- 매개변수가 3개인 생성자: name, price, stock
- 매개변수가 2개인 생성자: name, price (stock의 기본값은 0)
- 기본 생성자: 매개변수 없음 (name = "Unknown", price = 0, stock = 0)
코드 중복을 피하기 위해 this()를 사용하여 생성자들을 체이닝하세요.
치트 시트
생성자 오버로딩을 사용하면 동일한 클래스 내에 매개변수 목록이 다른 여러 생성자를 가질 수 있습니다.
여러 생성자 예시:
public class Book {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public Book(String title, String author) {
this.title = title;
this.author = author;
this.pages = 0;
}
}this()를 사용한 생성자 체이닝은 코드 중복을 피하기 위해 한 생성자에서 다른 생성자를 호출합니다:
public class Book {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public Book(String title, String author) {
this(title, author, 0); // 3개 매개변수 생성자 호출
}
public Book() {
this("Unknown", "Unknown"); // 2개 매개변수 생성자 호출
}
}사용법:
Book b1 = new Book("1984", "Orwell", 328);
Book b2 = new Book("Dune", "Herbert");
Book b3 = new Book();중요: this()는 생성자의 첫 번째 문장이어야 합니다.
직접 해보기
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
double price = Double.parseDouble(scanner.nextLine());
int stock = Integer.parseInt(scanner.nextLine());
Product product1 = new Product(name, price, stock);
Product product2 = new Product("Keyboard", 79.99);
Product product3 = new Product();
System.out.println("Product 1: " + product1.getName() + " - $" + product1.getPrice() + " (Stock: " + product1.getStock() + ")");
System.out.println("Product 2: " + product2.getName() + " - $" + product2.getPrice() + " (Stock: " + product2.getStock() + ")");
System.out.println("Product 3: " + product3.getName() + " - $" + product3.getPrice() + " (Stock: " + product3.getStock() + ")");
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
4상속
상속의 기초 (extends)super 키워드메서드 오버라이딩 (@Override)생성자 체이닝Object 클래스단일 및 다중 레벨 상속다중 클래스 상속이 불가능한 이유요약 - 직원 계층 구조