Thangnv
Thangnv

Reputation: 815

How to overload method running with other data type of parameters?

I have a short program to test overload method in java. This is my code:

public static void main(String[] args) {
    // TODO code application logic here
    // Case 1
    f2(5);
    // Case 2
    char x = 'a';
    f2(x);
    // Case 3
    byte y = 0;
    f2(y);
    // Case 4
    float z = 0;
    f2(z);
}

And there are my methods :

public static void prt(String s) {
    System.err.println(s);
}

public static void f2(short x) {
    prt("f3(short)");
}

public static void f2(int x) {
    prt("f3(int)");
}

public static void f2(long x) {
    prt("f5(long)");
}

public static void f2(float x) {
    prt("f5(float)");
}

and this is result:

f3(int)
f3(int)
f3(short)
f5(float)

I can't understand how does it running with case 2 and 3. Any explain for me ?

Upvotes: 0

Views: 1129

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213223

Method invocation in case of overloaded methods will invoke the most specific method based on the type parameters, and the actual type you pass.

Method invocation conversion follows the following path:

  • Identity Conversion: First the exact matching method will be searched. If found, it will be invoked. Conversion from a type to the same type.
  • Widening Primitive Conversion: If there is no exact matching method, the method is chosen based on the widening conversion from actual argument to format type parameter.

some more are there, not applicable here though. See JLS 5.3 for Method Invocation Conversion.

So, for f2(x); as there is no exact match for char type, so the method f2(int) is invoked, as the most specific type to which char can be converted by widening conversion is int. No, char to short is not a widening conversion.

Similary, for f2(y), there is no exact match for byte type, so the method f2(short) is invoked, as short is the most specific type that byte can be widened to.

See JLS 5.1.2 for Widening Primitive conversions:

19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double

Upvotes: 2

Related Questions