Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading methods

 
Badri Sarma
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}}
 
Rajeshwari Natarajan
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Badri Sarma
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks Rajeshwari, what would be the output for this
 
Yi Meng
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Badri Sarma
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, i am cleared at this concept now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic