


오버로딩(매개변수의 차이로만!)
메소드의 이름이 같고, 매개변수의 개수나 타입이 달라야 한다.
주의할 점은 '리턴 값만' 다른 것은 오버로딩을 할 수 없다는 것이다.
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
오버라이딩
부모 클래스로부터 상속받은 메소드를 자식 클래스에서 재정의하는 것
오버라이딩은 부모 클래스의 메소드를 재정의하는 것이므로, 자식 클래스에서는 오버라이딩하고자 하는 메소드의 이름, 매개변수, 리턴 값이 모두 같아야 한다
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("훌쩍훌쩍");
}
}
<결과>
흑흑 잉잉 훌쩍훌쩍