>  기사  >  Java  >  Java에서 재정의할 때 예외를 발생시키는 데 부모-자식 계층 구조가 중요합니까?

Java에서 재정의할 때 예외를 발생시키는 데 부모-자식 계층 구조가 중요합니까?

WBOY
WBOY앞으로
2023-08-19 13:49:231232검색

Java에서 재정의할 때 예외를 발생시키는 데 부모-자식 계층 구조가 중요합니까?

특정 메서드에서 발생한 (확인된) 예외를 처리하려면 Exception 클래스나 예외가 발생한 슈퍼클래스를 사용하여 이를 잡아야 합니다.

마찬가지로 슈퍼 클래스의 메서드를 재정의할 때 예외가 발생하는 경우 −

  • 하위 클래스의 메서드는 동일한 예외 또는 해당 하위 유형을 발생시켜야 합니다.

  • 하위 클래스의 메서드는 상위 유형을 삭제해서는 안 됩니다.

  • 예외를 발생시키지 않고 재정의할 수 있습니다.

Demo, SuperTest 및 Super 상속이라는 세 가지 클래스(계층 구조)가 있을 때 Demo와 SuperTest에 sample()이라는 메서드가 있는 경우.

Example

라이브 데모

class Demo {
   public void sample() throws ArrayIndexOutOfBoundsException {
      System.out.println("sample() method of the Demo class");
   }
}
class SuperTest extends Demo {
   public void sample() throws IndexOutOfBoundsException {
      System.out.println("sample() method of the SuperTest class");
   }
}
public class Test extends SuperTest {
   public static void main(String args[]) {
      Demo obj = new SuperTest();
      try {
         obj.sample();
      }catch (ArrayIndexOutOfBoundsException ex) {
         System.out.println("Exception");
      }
   }
}

Output

sample() method of the SuperTest class

예외를 포착한 클래스가 던져진 예외와 동일하지 않거나 예외의 슈퍼클래스가 아닌 경우 컴파일 타임 오류가 발생합니다.

마찬가지로 메서드를 재정의할 때 발생하는 예외는 재정의된 메서드나 해당 상위 클래스에서 발생하는 예외와 동일해야 합니다. 그렇지 않으면 컴파일 시간 오류가 발생합니다.

데모

import java.io.IOException;
import java.io.EOFException;
class Demo {
   public void sample() throws IOException {
      System.out.println("sample() method of the Demo class");
   }
}
class SuperTest extends Demo {
   public void sample() throws EOFException {
      System.out.println("sample() method of the SuperTest class");
   }
}
public class Test extends SuperTest {
   public static void main(String args[]) {
      Demo obj = new SuperTest();
      try {
         obj.sample();
      }catch (EOFException ex){
         System.out.println("Exception");
      }
   }
}

출력

Test.java:12: error: sample() in SuperTest cannot override sample() in Demo
public void sample() throws IOException {
            ^
overridden method does not throw IOException
1 error

D:\>javac Test.java
Test.java:20: error: unreported exception IOException; must be caught or declared to be thrown
   obj.sample();
              ^
1 error

위 내용은 Java에서 재정의할 때 예외를 발생시키는 데 부모-자식 계층 구조가 중요합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제