Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Core java

 
sahidul karim
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If i have two interfaces in which method is same but diffirent exception.one class is implementing both the interfaces.do i need to implement both the method in that class?
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only one is enough.Bacically what all it cares is about the signature of the method , not the exceptions that is throws.
 
karthikeyan Chockalingam
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following scenario





In the above case Implementor will compile... But if it was throwing SQLException as the compiler (or IDE) will show an error stating that the exception thrown is not compatible with InterfaceB
 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In the above case Implementor will compile... But if it was throwing SQLException as

code:

public int add(int x, int y) throws SQLException{

return x+y;
}

the compiler (or IDE) will show an error stating that the exception thrown is not compatible with InterfaceB


That's because while doing so you are not fulfilling one of the requirement for Overriding-

According to 'Java Language Specification',
  • A method declaration must not have a throws clause that conflicts with that of any method that it overrides. Otherwise, a compile-time error.
  • Overriding method must only throw an Exception that is more restrictive than overridden method.
  • Overriding method might decide not to thow any Exception.
  • Overriding method can throw RuntimeException & its subclasses.


  •  
    Burkhard Hassel
    Ranch Hand
    Posts: 1274
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi cowboys,

    What Prathiba wrote is the cause why you cannot throw any exception here.
    Even this:

    will not compile.



    Yours,
    Bu.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic