Re: Why this overloading example works this way?
- From: Chris Smith <cdsmith@xxxxxxx>
- Date: Tue, 5 Dec 2006 14:23:20 -0700
Gabriel Belingueres <gaby@xxxxxxxx> wrote:
final A p2 = new B();
o.method(p2);
Why the third method call is calling method(A) when the _final_
modifier is present in the local variable. I mean, since the local
variable is marked final, the compiler ALREADY KNOW, that for this
specific method call, we want to call the method with a B instance, not
an A instance.
The rules of the Java programming language state that method overloading
is based on the types of the variables passed as parameters. The type
of 'p2' is 'A', because you declared it that way. Therefore, the
overload with A as a parameter is called.
You seem to want the compiler to engage in some kind of reasoning
process to figure out that 'p2' must point to a B instance. Such a
language may be possible, but it's not Java. As for why Java doesn't do
that, one good reason is that the language behavior should be
predictable. The compiler can never completely reason out what objects
may be passed in to a method in the general case. The problem is
undecidable; there exists no software algorithm to do it. It could
guess correctly in certain simple cases, but there would always be the
outstanding question of whether some specific kind of reasoning is too
difficult or not. It would no longer be feasible for most programmers
to predict in advance what their programs will do. This is undesirable
for obvious reasons. Therefore, the language chooses a particularly
simple rule: find the variable declaration, and look at its (static)
type.
AFAIK, it is impossible to change the dynamic data type
of the p2 variable at runtime because it is marked final.
Yes, it is impossible at least from Java. Some fancy native code could
do it, given sufficient knowledge about the JVM implementation.
I can guess that this would introduce tricky rules to the language, but
I consider it as a nice to have feature for some future version of
Java. :)
It's a bit too late for this kind of change; it would potentially break
all sorts of existing code. There do exist other languages that
dispatch method calls dynamically on the basis of the types of
parameters. They are sometimes nice, but even then the rules for
resolving method calls can get complex.
--
Chris Smith
.
- Follow-Ups:
- Re: Why this overloading example works this way?
- From: Gabriel Belingueres
- Re: Why this overloading example works this way?
- References:
- Why this overloading example works this way?
- From: Gabriel Belingueres
- Why this overloading example works this way?
- Prev by Date: Re: How Do I Force the Browser to Save a File
- Next by Date: Re: Why this overloading example works this way?
- Previous by thread: Why this overloading example works this way?
- Next by thread: Re: Why this overloading example works this way?
- Index(es):
Relevant Pages
|