Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Overloading

 
Yogi Gupta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Pls go through the code below :

As per my understanding, the output of the above should be "Inside class Q4" but it is not. Can anyone explain this to me ?
thanks in advance,
yogesh
Edited by Corey McGlone: Added Code Tags
[ May 06, 2003: Message edited by: Corey McGlone ]
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch Yogi.
q4.method(10);
to decide which method it invokes search for a matching method in the compile type of "q4" that is "Test"
"Test.method(float)" matches the invocation.
could it have been overriding in a subclass? Yes it could because is not private, final, or static.
Was it overriden? No it was'nt. "Q4.method(int)" did not override it because the arguments are different. Thus the method in Test is called.
[ May 06, 2003: Message edited by: Jose Botella ]
 
Rajeshwari Natarajan
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is happening is method overloading not overriding. So it happens at compile time.
At compile time, the reference variable is of type Test. So the base class method public void method(float f) is invoked. The interger value passed is automatically promoted to float.
The base class has no idea of the method in derived class.
 
Todd Killingsworth
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For resolving method calls:
Overloading methods are determined using the compile -time reference type.
Overriding methods are determined using the run-time type of the object the reference points to.
In this case, the method is overloaded, reference q4 is of type Test, and 10 can be implicitly upcast from int to float.
Todd Killingsworth
 
Badri Sarma
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
what would be the oupput for this code
class Best{
public void method(float f) {
System.out.println("float");
}
public void method(double f) {
System.out.println("double");
}
public void method(long f) {
System.out.println("long");
}}
public class Test extends Best{
public void method(int i) {
System.out.println("Inside class Test");
}
public static void main(String xyz[]) { Best q4 = new Test();
q4.method(10);
}}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic