Overloading 오버로딩

  • Car 클래스 생성
  • 생성자 오버로딩이란 매개 변수를 달리하는 생성자를 여러 개 선언하는 것을 말한다
public class Car {
    //필드
    String company = "현대자동차";
    String model;
    String color;
    int maxSpeed;
    
    //생성자
    Car() {
        
    }
    
    Car(String model) {
        this.model = model;
    }
    
    Car(String model, String color) {
        this.model = model;
        this.color = color;
    }
    
    Car(String model, String color, int maxSpeed) {
        this.model = model;
        this.color = color;
        this.maxSpeed = maxSpeed;
    }
}
  • 실행 메서드
public class CarExample {
    public static void main(String[] args) {
        Car car1 = new Car();
        System.out.println(car1.company);
        // 현대자동차
        
        Car car2 = new Car("자가용");
        System.out.println(car2.company);
        System.out.println(car2.model);
        // 현대자동차, 자가용
        
        Car car3 = new Car("자가용", "빨강");
        System.out.println(car3.company);
        System.out.println(car3.model);
        System.out.println(car3.color);
        // 현대자동차, 자가용, 빨강
        
        Car car4 = new Car("택시", "검정", 200);
        System.out.println(car4.company);
        System.out.println(car4.model);
        System.out.println(car4.color);
        System.out.println(car4.maxSpeed);
        // 현대자동차, 택시, 검정, 200
    }
}

태그:

카테고리:

업데이트:

댓글남기기