오버 로딩 : 같은 메소드명을 가진 여러 개의 메소드를 작성하는 것
- 기본 생성자는public 클래스명() { }꼴로 정의
- 값을 초기화할 수 있음 (this.상태 = 기본값)
- 생성자 오버로딩은 기본 생성자에 parameter를 추가
- parameter의 개수, 타입이 다르면 다른 생성자
package ex04;
public class CheeseBurger {
    String name;
    int price;
    String sauce;
    // 기본 생성자 (치즈버거, 1000, 기본 양념)
    public CheeseBurger() {
        this.name = "CheeseBurger"; // 초기화
        this.price = 1000;
        this.sauce = "기본 양념";
    }
    public CheeseBurger(String sauce) {
        this.name = "CheeseBurger";
        this.price = 1000;
        this.sauce = sauce;
    }
    // 파라미터가 있는 생성자 > 생성자 오버로딩 (치즈버거, 1200, 케첩)
    public CheeseBurger(int price, String sauce) {
        this.name = "CheeseBurger";
        this.price = price;
        this.sauce = sauce;
    }
    public static void main(String[] args) {
        // 1. 기본 치즈버거 만들기
        CheeseBurger cb1 = new CheeseBurger();
        // 1-1. 출력
        System.out.println("메뉴 : " + cb1.name);
        System.out.println("가격 : " + cb1.price);
        System.out.println("소스 : " + cb1.sauce);
        System.out.println();
        // 2. 케첩이 들어간 치즈버거 만들기 (가격 : 200원 추가)
        CheeseBurger cb2 = new CheeseBurger(1200, "케첩");
        // 2-1. 출력
        System.out.println("메뉴 : " + cb2.name);
        System.out.println("가격 : " + cb2.price);
        System.out.println("소스 : " + cb2.sauce);
        System.out.println();
        // 3. 마요네즈가 들어간 치즈버거 만들기 (가격 : 1000원)
        CheeseBurger cb3 = new CheeseBurger("마요네즈");
        System.out.println("메뉴 : " + cb3.name);
        System.out.println("가격 : " + cb3.price);
        System.out.println("소스 : " + cb3.sauce);
        System.out.println();
    }
}

Share article