오버라이딩 (Overriding)
오버라이딩은 상속받은 클래스의 메서드의 내용만 재정의하는 것이다.
반환타입 메서드 이름(매개변수 선언) 형태다.
예시 int add (int x, int y) {}class Add {
int a, b;
public Add(int a, int b) {
this.a = a;
this.b = b;
}
int getResult() {
return a + b;
}
}
class Multi extends Add{
int c;
public Multi(int a,int b,int c) {
super(a,b);
this.c = c;
}
@Override
long getResult() {
return a+b+c;
}
}
메서드의 선언부가 같아야 하지만 선언부의 타입이 int와 long으로 달라
아래와 같은 컴파일 에러가 났다.
java: getResult() in Multi cannot override getResult() in Add return type long is not compatible with int
class Add {
int a, b;
public Add(int a, int b) {
this.a = a;
this.b = b;
}
void result() {
System.out.println("두 수의 덧셈 : " + (a + b));
}
}
class Multi extends Add {
int c;
public Multi(int a, int b, int c) {
super(a, b);
this.c = c;
}
@Override
void result() {
System.out.println("세 수의 덧셈 : " + (a + b + c));;
}
}
선언부가 같고 안의 내용물만 변경되어야 오버라이딩이 된다.
public class Main {
public static void main(String[] args) {
Add add = new Add(1,2);
Multi multi = new Multi(1,2,3);
add.result();
multi.result();
}
}
class Add {
int a, b;
public Add(int a, int b) {
this.a = a;
this.b = b;
}
void result() {
System.out.println("두 수의 덧셈 : " + (a + b));
}
}
class Multi extends Add {
int c;
public Multi(int a, int b, int c) {
super(a, b);
this.c = c;
}
@Override
void result() {
System.out.println("세 수의 덧셈 : " + (a + b + c));;
}
}
결과 값
두 수의 덧셈 : 3
세 수의 덧셈 : 6
헷갈리지 말 것