আমরা যখন কোনো পদ্ধতিকে ওভাররাইড করি তখন আমাদের কিছুনিয়ম অনুসরণ করতে হবে যা একটি ব্যতিক্রম নিক্ষেপ করে।
- যখন অভিভাবক শ্রেণীর পদ্ধতি শিশু শ্রেণীর পদ্ধতি কোনো ব্যতিক্রম নিক্ষেপ করে না কোনো চেক করা ব্যতিক্রম ফেলতে পারে না , কিন্তু এটি যেকোনো অচেক করা ব্যতিক্রম ফেলতে পারে .
class Parent {
void doSomething() {
// ...
}
}
class Child extends Parent {
void doSomething() throws IllegalArgumentException {
// ...
}
} - যখন প্যারেন্ট ক্লাস পদ্ধতি এক বা একাধিক চেক করা ব্যতিক্রম নিক্ষেপ করে , শিশু শ্রেণীর পদ্ধতি যেকোনো অচেক করা ব্যতিক্রম ফেলতে পারে .
class Parent {
void doSomething() throws IOException, ParseException {
// ...
}
void doSomethingElse() throws IOException {
// ...
}
}
class Child extends Parent {
void doSomething() throws IOException {
// ...
}
void doSomethingElse() throws FileNotFoundException, EOFException {
// ...
}
} - যখন অভিভাবক শ্রেণীর পদ্ধতি একটি আনচেক করা সহ একটি থ্রোস ক্লজ রয়েছে৷ ব্যতিক্রম , শিশু শ্রেণীর পদ্ধতি কোনটি বা যেকোন সংখ্যক অচেক করা ব্যতিক্রম ফেলতে পারে না , যদিও তারা সম্পর্কিত নয়।
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