my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Interface question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Interface question" Watch "Interface question" New topic
Author

Interface question

swapnil paranjape
Ranch Hand

Joined: May 15, 2005
Posts: 126
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

Joined: Dec 22, 2001
Posts: 13
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 ]

Kashif I. Khan
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
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.


SCJP 1.4, SCWCD 1.3, SCBCD 1.3
 
 
subject: Interface question