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

Interface question

 
swapnil paranjape
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am learing interfaces .
if the method declared in the interface is throwing exception .then the method in the class which implements this interface "Must" throw exception or need not throw exception?
eg:
public interface sample
{
public abstract void sampleMethod() throws Exception;
}
class test implents sample
{
//samplemethod here should throw expection or need not throw exception



please explain why?
 
Kashif Iqbal Khan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

Your class defination can look like


// approach 1.
public class SampleClass implements sample
{
public void sampleMethod() throws Exception{ // some implementation }
}

and also

// approach 2.
public class SampleClass implements sample
{
public void sampleMethod(){ // some implementation }
}

The overriding method needs not to add the "throws" clause however if it does it can only have exception of type Exception or any of its sub class (which in this case is any exception)
[ May 19, 2005: Message edited by: Kashif Iqbal Khan ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a general rule when you extend a class or implement an interface you can make changes that give the caller less to think about, but not things that give the caller more to think about.

If the interface declares an exception and the implementing class doesn't, the caller has no problem. The interface told him to handle an exception and you never throw one, no harm done.

If the interface declares "throws IOException" and you add an unrelated or more general exception, like "throws Exception", the caller using the interface won't know that exception type is coming. So the compiler just doesn't allow it. You can't force the caller to handle things that the interface didn't tell it about.
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that the implementing method can declare any unchecked exception in its throws clause. I'm not saying that this is good practice - it isn't - but it is legal.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic