매개변수의 유형과 개수가 다르게 하여 같은 이름의 메소드를 여러 개 가질 수 있게하는 기술
class MyClass2{
public int plus(int x, int y){
return x+y;
}
public int plus(int x, int y, int z){
return x + y + z;
}
public String plus(String x, String y){
return x + y;
}
}
public int plus(int i, int f){ //오류
return i+f;
//변수명은 다르지만, 매개변수의 타입과 개수가 동일한 메소드를 또 정의 할 수는 없다.
}
public MethodOverloadExam{
public static void main(String args[]){
MyClass2 m = new MyClass2();
System.out.println(m.plus(5,10));
System.out.println(m.plus(5,10,15));
System.out.println(m.plus("hello" + " world"));
}
}
- 생성자도 메소드와 마찬가지로 여러개를 선언할 수 있다.
public class Car{
String name;
int number;
public Car(){ // 기본 생성자
}
public Car(String name){
this.name = name;
}
public Car(String name, int number){
this.name = name;
this.number = number;
}
}
public class CarExam4{
public static void main(String args[]){
Car c1 = new Car();
Car c2 = new Car("소방차");
Car c3 = new Car("구급차", 1234);
}
}
public Car(){
this.name = "이름없음";
this.number = 0;
}
public Car(){
this("이름없음", 0);
}