posted 23 years ago
Hi Michael,
A very good and interesting question, indeed. It's a subtle point. These are the rules you need to look upon:
1. A class can have two methods with the same name, but with different set of arguments/arg types[overloaded methods] in any of the following 3 cases:
a. both methods are in the same subclass
b. both methods are in the super class
c. one is in superclass and one in subclass
2. If there are two methods with the same name, one in the superclass and one in the subclass, then, the method in the subclass should be given more preference.
3. If there are two methods available with the same name in a class, the method that is called is the method which has arguments that most exactly matches with the set of arguments passed upon.
Now, let us look at your example:
In your main, you call the subclass method with int argument. Now, since by Rule (2), the subclass method with double argument should be given more preference.
But, by Rule (3), the superclass method which takes int argument itself should be given more preference.
Hence, it is now not able to decide between Rules 2 and 3. Hence it results in a compilation error complaining of ambiguity.
Now, consider the following code:
<CODE>
class one
{
void method(float e)
{
System.out.println("one - float");
}
}
class two extends one
{
void method(int e)
{
System.out.println("two - int");
}
void method(String s)
{
System.out.println("two - string");
}
public static void main(String []a)
{
int i=5;
two r=new two();
r.method("hi");
r.method(i);
}
}
</CODE>
In the above case, you call subclass method with int as argument. Here none of the rules clash with each other. Hence, the subclass method with int argument is called.
Similarly, consider the following code:
<CODE>
class one
{
void method(int e)
{
System.out.println("one - int");
}
}
class two extends one
{
void method(int e)
{
System.out.println("two - int");
}
void method(String s)
{
System.out.println("two - string");
}
public static void main(String []a)
{
int i=5;
two r=new two();
r.method("hi");
r.method(i);
}
}
</CODE>
Here, too, there is no ambiguity as none of the 3 rules clash with one another, hence, it doesn't give a compilation error.
Hope I am clear. A good question, indeed!
Thanks,
Aparna