자바에서 오버라이딩 vs 오버로딩
소개
재정의 및 오버로드는 Java 프로그래밍의 핵심 개념입니다. 그것들은 Java 프로그램에서 다형성을 구현하는 방법입니다. 다형성은 OOPS 개념 중 하나입니다.
메서드 서명(이름 및 매개 변수)이 슈퍼 클래스와 자식 클래스에서 동일한 경우 오버라이딩이라고 합니다. 동일한 클래스에 있는 두 개 이상의 메서드가 이름은 같지만 매개변수가 다른 경우를 오버로딩이라고 합니다.
오버라이딩과 오버로딩 비교
Overriding | Overloading |
---|---|
Implements “runtime polymorphism” | Implements “compile time polymorphism” |
The method call is determined at runtime based on the object type | The method call is determined at compile time |
Occurs between superclass and subclass | Occurs between the methods in the same class |
Have the same signature (name and method arguments) | Have the same name, but the parameters are different |
On error, the effect will be visible at runtime | On error, it can be caught at compile time |
재정의 및 오버로딩 예제
다음은 Java 프로그램에서 오버로딩 및 재정의의 예입니다.
package com.journaldev.examples;
import java.util.Arrays;
public class Processor {
public void process(int i, int j) {
System.out.printf("Processing two integers:%d, %d", i, j);
}
public void process(int[] ints) {
System.out.println("Adding integer array:" + Arrays.toString(ints));
}
public void process(Object[] objs) {
System.out.println("Adding integer array:" + Arrays.toString(objs));
}
}
class MathProcessor extends Processor {
@Override
public void process(int i, int j) {
System.out.println("Sum of integers is " + (i + j));
}
@Override
public void process(int[] ints) {
int sum = 0;
for (int i : ints) {
sum += i;
}
System.out.println("Sum of integer array elements is " + sum);
}
}
재정의
Processor
의 process()
메서드 및 int i, int j
매개변수는 자식 클래스 MathProcessor
에서 재정의됩니다. 7행 및 23행:
public class Processor {
public void process(int i, int j) { /* ... */ }
}
/* ... */
class MathProcessor extends Processor {
@Override
public void process(int i, int j) { /* ... */ }
}
그리고 Processor
의 process()
메서드와 int[] ints
도 자식 클래스에서 재정의됩니다. 11행 및 28행:
public class Processor {
public void process(int[] ints) { /* ... */ }
}
/* ... */
class MathProcessor extends Processor {
@Override
public void process(Object[] objs) { /* ... */ }
}
과부하
process()
메서드는 Processor
클래스에서 오버로드됩니다. 7, 11, 15행:
public class Processor {
public void process(int i, int j) { /* ... */ }
public void process(int[] ints) { /* ... */ }
public void process(Object[] objs) { /* ... */ }
}
결론
이 기사에서는 Java의 재정의 및 오버로딩에 대해 설명했습니다. 오버라이딩은 슈퍼클래스와 자식 클래스의 메서드 시그니쳐가 같을 때 일어난다. 오버로딩은 동일한 클래스에 있는 두 개 이상의 메서드가 이름은 같지만 매개 변수가 다른 경우에 발생합니다.