Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritence basics

 
c weaves
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew, sorry for delayed reply.

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

Thanks again!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic