My Parent
class is :
import java.io.IOException;
public class Parent {
int x = 0;
public int getX() throws IOException{
if(x<=0){
throw new IOException();
}
return x;
}
}
I extend
this class to write a subclass Child
:
public class Child1 extends Parent{
public int getX(){
return x+10;
}
}
Notice while overriding the getX method in the Child
class , I have removed the throws
clause from the method definition .Now it results in an anomalous behavior by the compiler which is expected :
new Parent().getX() ;
does not compile without enclosing it in a try-catch
block , as expected .
new Child().getX() ;
compiles without enclosing it in a try-catch
block .
But the below lines of code needs the try-catch block .
Parent p = new Child();
p.getX();
As this could be foreseen i.e. using a parent class reference to invoke a child method during run-time polymorphism , why the designers of Java didn't make it mandatory to include the throws clause in the method definition while overriding a particular parent class method ? I mean if a parent class method has throws clause in its definition , then while overriding it the overriding method should also include the throws clause , Ain't it ?
When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the way by which java achieve Run Time Polymorphism.
Overridden methods can throw Exceptions, so long as the method being overridden also throws the same Exceptions. You can't introduce new Exceptions.
While a superclass method throws an exception while overriding it you need to follow the certain rules. According to the 3rd rule, if the super-class method throws certain exception, you can override it without throwing any exception.
No, this is appropriate - an overridden method can be more restrictive about what it throws (and returns) because this can be useful for callers who know at compile time that they'll be using the overridden method, and don't want to bother with exceptions which can't happen etc. It has to be more restrictive rather than more permissive though, so that it can't surprise callers who do access it through the parent declaration.
Using the overridden method via a reference of type Parent
is never going to violate the contract of "it might throw IOException
" - the absence of an exception doesn't violate the contract. The other way round (if the parent didn't declare the exception, but the overriding method does) would be a contract violation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With