2

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?

1
  • 1
    the method bar throws an exception and you are not handling it... Commented Jul 10, 2015 at 14:51

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.