Click to See Complete Forum and Search --> : Method overloading - please clarify


DeviPrasad
August 13th, 1999, 09:30 AM
hai everybody,
i have a problem which most of u might find useful. It is regarding method overloading. Pls look at the following code

/////////////////////////////////
// This doesnot compile at all //
/////////////////////////////////

public class EqualsTest2
{
public static void main(String args[])
{
MyClass1 c1 = new MyClass1();
System.out.println(c1.equals(null)); //Ambiguous call to method equals
}
}

class MyClass
{
public boolean equals(MyClass mc)
{
System.out.println("Equals of MyClass called");
System.out.println("mc instanceof MyClass ? " + (mc instanceof MyClass));
return true;
}
}

class MyClass1 extends MyClass
{
public boolean equals(Object mc)
{
System.out.println("Equals of MyClass1 called");
System.out.println("mc instanceof Object ? " + (mc instanceof Object));
return true;
}
}




But now consider these codes

public class EqualsTest3
{
public static void main(String args[])
{
MyClass1 c1 = new MyClass1();
System.out.println(c1.equals(null));
}
}

class MyClass
{
public boolean equals(Object mc)
{
System.out.println("Equals of MyClass called");
System.out.println("mc instanceof MyClass ? " + (mc instanceof MyClass));
return true;
}
}

class MyClass1 extends MyClass
{
public boolean equals(MyClass1 mc)
{
System.out.println("Equals of MyClass1 called");
System.out.println("mc instanceof Object ? " + (mc instanceof Object));
return true;
}
}



Now this code compiles successfully and calls the method equals(MyClass) of the class MyClass1. How can this be explained ?

Also consider this code

public class EqualsTest4
{
public static void main(String args[])
{
MyClass1 c1 = new MyClass1();
System.out.println("c1.equals(null) ");
c1.equals(null);
System.out.println("c1.equals(c1) ");
c1.equals(c1);
}
}

class MyClass1
{
public boolean equals(Object mc)
{
System.out.println("Equals with Object called");
System.out.println("mc instanceof Object ? " + (mc instanceof Object));
System.out.println("mc instanceof MyClass1 ? " + (mc instanceof MyClass1));
return true;
}

public boolean equals(MyClass1 mc)
{
System.out.println("Equals with MyClass1 called");
System.out.println("mc instanceof Object ? " + (mc instanceof Object));
System.out.println("mc instanceof MyClass1 ? " + (mc instanceof MyClass1));
return true;
}
}



Even this one compiles and the method equals(MyClass1 mc) is called. But the output generated is

mc instanceof Object ? false
mc instanceof MyClass1 ? false

How can u explain this behaviour ?

Please help. I am not able to find out the reason in any book also.

thank you,
Devi Prasad M. P.

Keep smiling!!!
Keep working hard!!!
Keep climbing high!!!