Wednesday, 2 October 2013

Unclear Compile-time Java Exception

Unclear Compile-time Java Exception

I'm running into peculiar behavior in terms of compile time exceptions
with the following code (I'm using JDK7):
public class classA { public void foo( List<Object> o ){} }
public classB<T>{ public void bar( List<Object> o ){} }
We consider the the following test object
List<String> o = new ArrayList<String>();
There is no way to get java to compile by passing o as a parameter to the
method foo of class classA, and as far as I can figure, there shouldn't
be.
Now say we're in the main method of classB and try to just call bar
without instantiating an instance of classB to call it on. I might expect
to get a non-static method can't be called from static context compilation
error like I would if I tried to pull that in classA, but instead I get a
conversion invocation error. That, makes sense - the types don't line up.
However if I try call bar from a nonstatic context, as in
ClassB b = new classB();
b.bar( o );
Java seems to forgive me for not lining up the types and runs the code no
problem. I haven't done anything to fix the issue of typcasting, so why
does Java let this code execute, where it wouldn't with classA?

No comments:

Post a Comment