Compiler design decision for dynamic method invocation
I asked about Compiler interpretation of overriding vs overloading on
StackOverflow, and got good answers, but this led me to another question
that I'm not sure is appropriate for SO, but I think is for here.
One should read the original question and accepted answer, but perhaps
it's understandable just by looking at the code below:
public static void whatIs(Circle s)
{
System.out.println("Circle");
}
public static void whatIs(Square s)
{
System.out.println("Square");
}
and we attempt to call,
whatIs(shapes[0]); //array of Shape objects (interface implemented by
Circle,Square)
whatIs(shapes[1]);
we will get two errors (one for Square and one for Circle) indicating that:
method Driver.whatIs(Square) is not applicable
actual argument Shape cannot be converted to Square by method invocation
conversion
As is suggested in my question, using instanceof can give the desired
results, and as the answered suggested:
The compiler could auto generate code like
if (shapes[0] instanceof Circle)
{
whatIs((Circle) shapes[0]); //prints "Circle"
}
but, it does not. Just to be clear, I know one can use an abstract class
instead of an interface to achieve similar functionality, nonetheless,
does anyone know why the Java compiler won't automatically do this for
you? I'm not a compilers guy, but I have a feeling that this is not an
opinion based question. I assume that there is a good reason for this
decision.
No comments:
Post a Comment