it is said that overloading have compile time binding in java but actually object created at run time so I am confused how compile time binding take place.
+1
A:
It means that the compiler works out which overload to use based solely on the compile-time type of the expressions involved. Sample code:
class Parent
{
void foo(Object x)
{
System.out.println("Parent.foo(Object)");
}
}
class Child extends Parent
{
void foo(String x)
{
System.out.println("Child.foo(String)");
}
}
public class Test
{
public static void main(String[] args)
{
Child c = new Child();
c.foo("hello"); // Calls Child.foo(String)
Parent p = c;
p.foo("hello"); // Calls Parent.foo(Object)
}
}
Note how the declared type of the variable (Parent
or Child
for p
and c
respectively) determines which overloads are considered.
Note that this is not the same as overriding, which is based on the execution-time type of the target object.
Jon Skeet
2010-08-11 09:19:43
if we swap the method of Parent and Child than why its giving compile time error "The method foo(Object) is ambiguous for the type Child". in c.foo("hello") line.
Vivart
2010-08-11 13:41:16
@Vivart: Because at that point the compiler is balancing two ways in which an overload can be "better" - a method declared in a subclass is preferred to a method declared in a superclass, but a method with a more specific parameter (e.g. String) is preferred to one with a more general parameter (e.g. Object).
Jon Skeet
2010-08-11 13:44:34
thanks jon i got it.
Vivart
2010-08-11 13:57:10