Skip to content

Day 13(21.09.17)

Byeong Gwan Seo edited this page Sep 17, 2021 · 7 revisions

19. 생성자와 메소드 오버로딩(Overload)

(1) 생성자의 오버로딩

외부에서 다양한 데이터가 제공될때, 이를 이용해서 객체를 초기화 하려면 생성자도 다양해질 필요가 있다. 예를 들어, 공장에서 자동차를 찍어낸다고 가정할때, 모델명만 들어오거나, 모델명과 색상이 같이 들어오거나, 색상만 들어온다고 해서 자동차를 안 만들수는 없는 노릇 아닌가? 마찬가지로 생성자가 하나밖에 없다면 다양한 데이터를 활용하기에 어려움이 발생할 수 있다. 생성자의 오버로딩은 이럴때 사용하는 것으로, 매개변수를 달리하는 생성자는 여러개 선언하는 것을 말한다.
다음은 Car 클래스에서의 생성자 오버로드 예시이다.

public class Car {
 Car() {} // 기본 생성자
 Car(String model) {}
 Car(String model, String color){}
 Car(String model, String color, int maxSpeed){}
}

여기서 눈에 띄는 점은, 위에서 말했듯이 생성자마다 매개변수의 종류가 다르다는 점이다. 이 부분은 생성자 오버로드에서 중요한 부분인데, 매개 변수의 순서만 다르고 동일한 경우엔 생성자 오버로딩이라고 볼 수 없다. 즉, 위의 생성자에

 Car (String color, String model){}

이 생성자를 선언한다고 해도 생성자 오버로딩에 해당하지 않고 컴파일 에러가 발생하게 된다. 다음 예시는 위에 예시로 든 생성자 오버로딩을 사용하여 여러개의 객체를 생성하는 프로그램을 작성한 것이다.

public class Car {
//field
String company = "Hyundai" //이렇게 클래스의 필드에서 초기화를 선언하면 해당 클래스에서 생성되는 모든 Car 객체의 제조사는 Hyundai로 고정된다.
String model;
String color;
int maxSpeed;

//constructor
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;
 }
}  
```java
public class CarExample {
 public static void main(String[] args) {
  Car car1 = new Car();
  System.out.println("car1.company: " + car1.company);
  System.out.println();

  Car car2 = new Car("Avante");
  System.out.println("car2.company: " + car2.company);
  System.out.println("car2.model: " + car2.model);
  System.out.println();

  Car car3 = new Car("Grandeur", "Red");
  System.out.println("car3.company: " + car3.company);
  System.out.println("car3.model: " + car3.model);
  System.out.println("car3.color: " + car3.color);
  System.out.println();

  Car car4 = new Car("Sonata", "Silver", 200);
  System.out.println("car4.company: " + car4.company);
  System.out.println("car4.model: " + car4.model);
  System.out.println("car4.color: " + car4.color);
  System.out.println("car4.maxSpeed: " + car4.maxSpeed);
 }
}

Clone this wiki locally