GiantStepDEV

μƒμ„±μž(constructor)

클래슀λ₯Ό 객체둜 λ§Œλ“€λ•Œ μžλ™μœΌλ‘œ 호좜(=newλ₯Ό ν˜ΈμΆœν•  λ•Œ)되며, μƒμ„±μžλŠ” μΈμŠ€ν„΄μŠ€ ν•„λ“œλ₯Ό μ΄ˆκΈ°ν™” 함.
μƒμ„±μžλŠ” μΈμŠ€ν„΄μŠ€ ν•„λ“œλ₯Ό μ΄ˆκΈ°ν™”ν•˜λŠ” 것이 λͺ©μ μž„.

μƒμ„±μž 생성 κ·œμΉ™

  • μƒμ„±μžλŠ” 클래슀 이름과 κ°™μ•„μ•Ό 함.
  • λ°˜ν™˜νƒ€μž… μ—†κ³  μ ‘κ·Όμ œν•œμžλ§Œ 올 수 μžˆμœΌλ‚˜ private은 νŠΉλ³„ν•œ κ²½μš°κ°€ μ•„λ‹ˆλ©΄ μ‚¬μš© μ•ˆ 함.
  • ν•˜λ‚˜μ˜ ν΄λž˜μŠ€λŠ” μ—¬λŸ¬κ°œμ˜ μƒμ„±μžλ₯Ό κ°€μ§ˆ 수 있음. 단, μ˜€λ²„λ‘œλ”© 생성 κ·œμΉ™μ— λ§žμ•„μ•Ό 함.

μ˜€λ²„λ‘œλ”© κ·œμΉ™

  • 데이터 νƒ€μž…μ΄ 같아도 κ°―μˆ˜κ°€ λ‹€λ₯΄λ©΄ κ°€λŠ₯
  • 데이터 νƒ€μž…μ΄ κ°™κ³  κ°―μˆ˜κ°€ 같을 경우, λ³€μˆ˜λͺ…이 달라도 μ†Œμš©μ—†μŒ.
μ˜€λ²„λ‘œλ”©μ— λŒ€ν•΄μ„œλŠ” λ©”μ†Œλ“œμ—μ„œ μžμ„Ένžˆ λ‹€λ£° μ˜ˆμ •
package μƒμ„±μžκΈ°λ³Έμ—°μŠ΅0111;

public class ConstructorEx {
    public static void main(String[] args) {
        Car casper = new Car(); // 아무것도 μ—†λŠ” μƒμ„±μž 호좜
        Car kona = new Car("μ½”λ‚˜");
        Car sorento = new Car("μ˜λ Œν† ","2023");
        Car avante = new Car("μ•„λ°˜λ–Ό","2019","White");

        casper.getCar();
        kona.getCar();
        sorento.getCar();
        avante.getCar();
    }
}

class Car {
    // μΈμŠ€ν„΄μŠ€ ν•„λ“œ
    String name;
    String year;
    String color;

    // 아무것도 μ—†λŠ” μƒμ„±μž
    public Car() {}

    public Car(String name) {
        this.name = name;
    }
    public Car(String name, String year){
        this.name = name;
        this.year = year;
    }
    public Car(String name, String year, String color) {
        this.name = name;
        this.year = year;
        this.color = color;
    }

    // 일반 λ©”μ†Œλ“œλŠ” λ°˜ν™˜νƒ€μž… κΌ­ μ μ–΄μ€˜μ•Ό 함.
    void getCar() {
        System.out.println("이름 : " + name);
        System.out.println("연식 : " + year);
        System.out.println("색상 : " + color);
        System.out.println("------------------");
    }

}
profile

GiantStepDEV

@kongmi

ν¬μŠ€νŒ…μ΄ μ’‹μ•˜λ‹€λ©΄ "μ’‹μ•„μš”β€οΈ" λ˜λŠ” "κ΅¬λ…πŸ‘πŸ»" ν•΄μ£Όμ„Έμš”!