• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Throws, in inheritance !

 
Prathamesh Gaddam
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

1. Please clarify why the inherited/overriding method in the sub-class can skip the 'throws' for an exception, though vice versa is compile error. Refer code.

2.Does the overriding/inherited method need to only throw the same exception or it specialized exception, because in the following e.g if the class B throws 'Throwable', compile error.



3. Towards above example, please clarify in accordance to these statements:
i) A a = new B(); a.process(); ERROR
ii) B b = new B(); b.process(); COMPLIES

Thank you in advance !
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using your example, consider what happens when you have a method that returns an A:


However since A and B are both types of A, the getMyA() method can legally return a B. The calling code doesn't really know or care what the runtime class the getMyA() method returns, as long as it can be used like any other A.


Since a subclass of A should be able to be used anywhere an A can be used then it follows that:
  • An overriding method in a subclass can always throw fewer checked exceptions than the method it overrides.
  • An overriding method in a subclass can never throw more checked exceptions than the method it overrides.

  • For additional reading on this subject, google Liskov Substitution Principal
     
    amitabh mehra
    Ranch Hand
    Posts: 98
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Prathamesh Gaddam:
    3. Towards above example, please clarify in accordance to these statements:
    i) A a = new B(); a.process(); ERROR
    ii) B b = new B(); b.process(); COMPLIES

    Thank you in advance ![/QB]


    Rule:When a subclass overrides a method from super class, it can only specify all or a subset of the exception classes thrown in the overridden method of the super class.

    If this restriction was not there, then in your i) case, while compiling, compiler checks the process() method of A for exceptions since the reference type is of A type. But the process() in A says that an exception is to be thrown. So it will be a breach of contract at runtime.

    Hence the check during compile time.
     
    Ilja Preuss
    author
    Sheriff
    Posts: 14112
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Google for the Liskov Substitution Principle - that is describing the whole reason for this behavior.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic