1. 오버로딩
- 메소드에서 매개변수만 다르면 얼마든지 저의하고 사용이 가능
- 메소드의 이름이 같아야함
- 매개변수의 개수나 타입이 달라야함
- 리턴값만 다르면 오버로딩이 불가능
- 매개변수의 차이로만 구현 가능
class OverloadingTest {
public static void main(String[] args) {
OverloadingMethods om = new OverloadingMethods();
om.print();
System.out.println(om.print(3));
om.print("Hello!");
System.out.println(om.print(4, 5));
}
}
class OverloadingMethods {
public void print() {
System.out.println("오버로딩1");
}
String print(Integer a) {
System.out.println("오버로딩2");
return a.toString();
}
void print(String a) {
System.out.println("오버로딩3");
System.out.println(a);
}
String print(Integer a, Integer b) {
System.out.println("오버로딩4");
return a.toString() + b.toString();
}
}
결과
오버로딩1
오버로딩2
3
오버로딩3
Hello!
오버로딩4
45
오버로딩의 사용이유
1) 같은 기능을 하는 메소드를 하나의 이름으로 사용가능
2) 메소드의 이름 절약 가능
2. 오버라이딩
- 부모 클래스에서 상속받은 메소드를 자식클래스에서 재정의
- 메소드의 이름, 매개변수, 리턴값이 모두 같아야 함
public class OverridingTest {
public static void main(String[] args) {
Person person = new Person();
Child child = new Child();
Senior senior = new Senior();
person.cry();
child.cry();
senior.cry();
}
}
class Person {
void cry() {
System.out.println("흑흑");
}
}
class Child extends Person {
@Override
protected void cry() {
System.out.println("잉잉");
}
}
class Senior extends Person {
@Override
public void cry() {
System.out.println("훌쩍훌쩍");
}
}
결과
흑흑
잉잉
훌쩍훌쩍
오버로딩 vs 오버라이딩
한마디로 정의하면
오버로딩은 '기존에 없는 새로운 메소드를 추가'
오버라이딩은 '상속받은 메소드를 재정의'
