| Author |
Overloading methods
|
Badri Sarma
Ranch Hand
Joined: Apr 01, 2003
Posts: 72
|
|
Hi, what would be the output for the below 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
|
 |
Rajeshwari Natarajan
Ranch Hand
Joined: Mar 05, 2003
Posts: 67
|
|
The o/p will be - long, since the method invoked is public void method(long f). The reference variable is of base class type and hence one of the 3 methods in base class should be called. The argument passed will be promoted to the closest matching type. Here int will be promoted to long. If 10.0 was passed as argument, the o/p will be double since the default type of floating point values is double. If 10.0f was passed as argument, the o/p will be float.
|
regards<br />Rajeshwari. N
|
 |
Badri Sarma
Ranch Hand
Joined: Apr 01, 2003
Posts: 72
|
|
Hi, Thanks Rajeshwari, what would be the output for this
|
 |
Yi Meng
Ranch Hand
Joined: May 07, 2003
Posts: 270
|
|
o/p will be float since the reference used to invoke methods at compile time is of type Best and thus the compiler does not anything about Best's subclasses..... The only method the compiler knows about Best is ..method(float f) and at runtime 10 is implictly castes to float. You may try something like : ---------- class Best{ public void method(float f) { System.out.println("float"); } } class Test extends Best{ public void method(double i) { System.out.println("Inside class Test"); } public static void main(String xyz[]) { Best q4 = new Test(); q4.method(10.0); } } ------------- btw, compilation fails in this case.
|
Meng Yi
|
 |
Badri Sarma
Ranch Hand
Joined: Apr 01, 2003
Posts: 72
|
|
Thanks, i am cleared at this concept now
|
 |
 |
|
|
subject: Overloading methods
|
|
|