Overloading에 대해 알아보자
오버로딩(Overloading)이란 매개변수의 타입, 개수, 순서가 다른 생성자를여러 개 선언하는 것을 말한다.
public class ConstructorClass {
String name = "sally";
String color;
String job;
int age;
ConstructorClass() {}
ConstructorClass(String color) {
this.color = color;
}
ConstructorClass(String color, String job) {
this.color = color;
this.job = job;
}
ConstructorClass(String color, String job, int age) {
this.color = color;
this.job = job;
this.age = age;
}
}
ConstructorClass() {} 와 같이 매개변수가 없는 생성자를 기본 생성자라고 한다. 기본생성자는 따로 생성하지 않아도 컴파일러가 만들어준다
위의 코드를 보면 매개변수가 없는 기본 생성자를 만들었다.
그 이유는 매개변수가 있는 다른 생성자를 만들면 컴파일러가 기본 생성자를 만들지 않기 때문에 따로 선언해줄 필요가 있기 때문이다.
ConstructorClass(String color) {
this.color = color;
}
ConstructorClass(String color, String job) {
this.color = color;
this.job = job;
}
ConstructorClass(String color, String job, int age) {
this.color = color;
this.job = job;
this.age = age;
}
ConstructorClass(String color)
ConstructorClass(String color, String job)
ConstructorClass(String color, String job, int age)
위의 코드를 보면 각 생성자의 매개변수의 타입, 개수가 다르기 때문에 오버로딩이 맞다.
오버로딩이 아닌 코드를 살펴보자
ConstructorClass(int age, String job, String color) {
this.color = color;
this.job = job;
this.age = age;
}
ConstructorClass(int age, String color, String job) {
this.color = color;
this.job = job;
this.age = age;
}
위의 코드를 살펴보면 매개변수의 타입이 int, String으로 순서가 동일하고 매개변수의 개수도 세개로 동일하다.
String type의 경우 매개변수의 이름만 바뀌었을 뿐 동일하다
오버로딩의 경우 매개변수명은 중요하지 않다
String 타입의 매개변수명의 순서가 다르다고 해서 오버로딩인 것은 아니다
ConstructorClass(String name, String color) {}
ConstructorClass(String color, String name) {}
위의 코드도 마찬가지로 매개변수의 타입과 개수가 동일하기 때문에 오버로딩이 아니다.
초기화 내용이 비슷한 생성자들에서 중복코드가 발생할 수 있는데 이 점은 다른 생성자를 호출하는 this()로 해결한다
ConstructorClass(String color) {
this(color, null, 0);
}
ConstructorClass(String color, String job) {
this(color,job,0);
}
ConstructorClass(String color, String job, int age) {
this.color = color;
this.job = job;
this.age = age;
} //공통실행 코드
초기화 내용은 한 생성자에 몰아서 작성해준다.
즉, 공통 실행코드로 빼준다
ConstructorClass(String color, String job, int age) {
this.color = color;
this.job = job;
this.age = age;
}
다른 생성자에서는 this로 공통 실행코드를 호출한다
매개변수는 공통 실행코드에서 받는 매개변수에 맞게 호출해줘야 한다
ConstructorClass(String color) {
this(color, null, 0);
}
ConstructorClass(String color, String job) {
this(color,job,0);
}
this로 다른 생성자를 호출할때는 생성자의 제일 첫번째에 와야한다
ConstructorClass(String color) {
System.out.println("color");
this(color, null, 0);
}
ConstructorClass(String color, String job) {
System.out.println("color, job");
this(color,job,0);
}
위의 코드처럼 this를 호출하기 전에 다른 실행문을 먼저 쓰면 오류가 발생한다
ConstructorClass(String color) {
this(color, null, 0);
System.out.println("color");
}
ConstructorClass(String color, String job) {
this(color,job,0);
System.out.println("color, job");
}
위의 코드는 this 호출문이 생성자의 제일 첫 줄에 있기 때문에 문제 없는 코드다