메서드를 재정의할 때 몇 가지 규칙을 따라야 합니다. 예외가 발생합니다.
- 상위 클래스 메서드 예외를 던지지 않음, 하위 클래스 메소드 확인된 예외를 throw할 수 없습니다. 하지만 확인되지 않은 예외가 발생할 수 있습니다. .
class Parent {
void doSomething() {
// ...
}
}
class Child extends Parent {
void doSomething() throws IllegalArgumentException {
// ...
}
} - 상위 클래스 메서드인 경우 하나 이상의 확인된 예외 발생 , 하위 클래스 메소드 모든 확인되지 않은 예외를 throw할 수 있습니다. .
class Parent {
void doSomething() throws IOException, ParseException {
// ...
}
void doSomethingElse() throws IOException {
// ...
}
}
class Child extends Parent {
void doSomething() throws IOException {
// ...
}
void doSomethingElse() throws FileNotFoundException, EOFException {
// ...
}
} - 상위 클래스 메서드가 선택되지 않은 throws 절이 있습니다. 예외 , 하위 클래스 메소드 확인되지 않은 예외를 발생시키지 않거나 여러 개 발생시킬 수 있습니다. , 관련이 없는 경우에도 마찬가지입니다.
class Parent {
void doSomething() throws IllegalArgumentException {
// ...
}
}
class Child extends Parent {
void doSomething() throws ArithmeticException, BufferOverflowException {
// ...
}
} 예
import java.io.*;
class SuperClassTest{
public void test() throws IOException {
System.out.println("SuperClassTest.test() method");
}
}
class SubClassTest extends SuperClassTest {
public void test() {
System.out.println("SubClassTest.test() method");
}
}
public class OverridingExceptionTest {
public static void main(String[] args) {
SuperClassTest sct = new SubClassTest();
try {
sct.test();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
} 출력
SubClassTest.test() method