Created
July 22, 2019 11:42
-
-
Save Kaushal28/3107e25c9f06d7e36eef200a36878d97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Rule #1: | |
* If the super-class overridden method does not throw an exception, | |
* subclass overriding method can only throws the unchecked exception, | |
* throwing checked exception will lead to compile-time error. | |
* | |
* Rule #2: | |
* If the super-class overridden method does throws an exception, subclass | |
* overriding method can only throw same, subclass exception. Throwing parent | |
* exception in Exception hierarchy will lead to compile time error. Also there | |
* is no issue if subclass overridden method is not throwing any exception. | |
* | |
*/ | |
class ParentClass { | |
void method1 () { | |
System.out.println("parent method1"); | |
} | |
void method2 () { | |
System.out.println("parent method1"); | |
} | |
void method3 () throws RuntimeException{ | |
System.out.println("parent method3"); | |
} | |
} | |
class ChildClass { | |
@Override | |
void method1 () throws ArithmeticException{ | |
System.out.println("child method1"); | |
} | |
// Throwing checked exception will give compilation error | |
// @Override | |
// void method2 () throws Exception | |
// System.out.println("child method2"); | |
// } | |
/** | |
* This method can throw the same exception (RunTimeException), can throw subclass of | |
* the parent thrown exception like (ArithmaticException), can throw no exceptions but | |
* it can't throw parent of RunTimeException (Here) in exception hierarchy (e.g. Exception). | |
* This will give compilation error. | |
*/ | |
@Override | |
void method3 () { | |
System.out.println("child method3"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment