Jaja
Jaja

Reputation: 105

Need explanation regarding interfaces and methods in Java

Take a look at this code:

public interface Foo {
    public void bar() throws Exception;
}

public class FooImpl implements Foo {
     public void bar() {
}

public static void main(String args[]) {
    Foo foo = new FooImpl();
    foo.bar();
}

Why would I get an "unhandled exception type" compilation error, whereas if I changed

Foo foo = new FooImpl();

to

FooImpl foo = new FooImpl();

I wouldn't get any error?

From my understanding, public methods use dynamic binding, so shouldn't the original code call FooImpl 's bar() method as well?

Upvotes: 2

Views: 74

Answers (3)

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

The point is that you can reduce the exception list thrown from a method which you override (implement in case of interfaces). This does not break the contract of the class.

Now, when you are using the reference to the interface, the compiler sees that the method invoked is declared to throw exception, so you have to handle it.

However, if you use the reference to the implementing class, the compiler sees that you have reduced the exception list on the implemented/overridden method because your implementation does not throw that Exception at all, so there is no point to force you to handle something that is never thrown.

Upvotes: 1

khelwood
khelwood

Reputation: 59096

You have declared that Foo::bar may throw a checked exception, so if your variable is declared of type Foo, then you have to handle the possibility of an exception.

You have declared that FooImpl::bar does not throw a checked exception, so if your variable is declared of type FooImpl, then you do not have to handle the possibility of an exception.

The point of polymorphism is that if your variable is of type Foo, then the code that calls bar does not know what implementation of the method it is getting; it only knows what Foo declares about the method.

Upvotes: 0

Joe
Joe

Reputation: 31057

Foo#bar throws a checked exception; FooImpl#bar does not, despite overriding bar. javac considers the static type when determining if your code needs to catch exceptions.

Upvotes: 3

Related Questions