*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method Overloading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Method Overloading" Watch "Method Overloading" New topic
Author

Method Overloading

Yogi Gupta
Greenhorn

Joined: Apr 21, 2003
Posts: 4
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

Joined: Jul 03, 2001
Posts: 2120
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 ]

SCJP2. Please Indent your code using UBB Code
Rajeshwari Natarajan
Ranch Hand

Joined: Mar 05, 2003
Posts: 67
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.


regards<br />Rajeshwari. N
Todd Killingsworth
Greenhorn

Joined: Jan 30, 2002
Posts: 28
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

Joined: Apr 01, 2003
Posts: 72
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);
}}


Thanks<br />Badri
 
Don't get me started about those stupid light bulbs.
 
subject: Method Overloading
 
Similar Threads
Overloading methods
Interfaces
Math.abs()
Can anyone see this...
Accessing Base class version of overridden method