File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inheritence basics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inheritence basics" Watch "Inheritence basics" New topic

Inheritence basics

c weaves

Joined: Aug 04, 2011
Posts: 11
Slightly confused, the code below compiles fine (imports are not included), it defines a method throwIt() in the interface which throws a checked IO Exception, class C implements interface I and is allowed to redefine the throwIt() method without the IO Exception, why is this allowed? The InheritenceTest class is then able to implement and call the throwIt() method without having to catch the IOException. I thought if the interface defines certain behaviour then the sub classes have to honour it? Obviously it has something to do with class C redefining the interface method and dropping the throw declaration but why is this allowed?

Thank you!!
Matthew Brown

Joined: Apr 06, 2010
Posts: 4541

You're allowed to throw fewer (or more specific) exceptions when you implement or override a method, because there's no danger in doing this. You're still satisfying the Liskov Substitution Principle, because you can always use an instance of the class in any situation where an instance of the interface is needed.

But allowing more (or more general) exceptions isn't allowed, because it would allow the following unsafe code:

It's very similar to return types when overriding. You can (as of Java 1.5) return a more specific type in the overriding method. But you can't return a more general type.
c weaves

Joined: Aug 04, 2011
Posts: 11
Matthew, sorry for delayed reply.

Excellent answer thank you, helped clear up the issue!!

Thanks again!
I agree. Here's the link:
subject: Inheritence basics
It's not a secret anymore!