1

Below is the java code of overloading.

public class Main {

    public static void main(String args[]){

        Main m = new Main();
        char c  = 'a';
        m.sum(c);
    }

     public void sum(int c){
            System.out.println("A");
     }

     public void sum(Object c){
          System.out.println("B");
     }
}

Output is "A" but why I did not understand.

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
  • 9
    because c is not an Object, but can be read as an int by the compiler – Stultuske May 23 '19 at 06:09
  • 3
    Did you have a different expectation? Did you have a reason for that? Please do not ask "Explain this code." questions. They are considered "too broad" because they do not match the idea of asking clear question about specific programming problems. – Yunnosch May 23 '19 at 06:12

3 Answers3

4

We are passing a char primitive as argument for the method sum.

The method sum(int c) is called because char is a subtype of int (char <: int), so there is a widening conversion from char to int. Other primitives will have a similar behavior, and their subtype relationship is given by:

byte <: short <: int <: long <: float <: double; and char <: int

I think you are wondering why the method sum(Object c) is not called. Suppose we remove method sum(int c), now sum(Object c) will be called. This is because the char primitive will be autoboxed into a Character object, and Character is a subtype of Object.

However, in the given code, autoboxing will not occur here because there is a method available that takes in int (a supertype of char), which is more preferable.

Teik Jun
  • 371
  • 2
  • 12
1

Adding to Stultuske's answer. It goes to the sum(int c) because char is not an Object. The link below explains(or gives an example of) why this transition from char to int works. specifically "If we direct assign char variable to int, it will return ASCII value of given character."

https://www.javatpoint.com/java-char-to-int

  • You mean it will return the UTF-16 code unit value, which may not be a whole character, as in `"".charAt(0)` and `"".charAt(1)`. – Tom Blodget May 23 '19 at 16:44
1

There is a distinction between a class and a primitive data type in java. All objects (belonging to different classes) are instances of the Object class and thus would go to the second function. However, char and int are not instances of Object. They will not go into the second function.
Char is a 16 bit integer and thus is converted to an int.
You can see a change in output by adding a third function,

public void sum(char c) {
    System.out.println("B");
}

This is because of the hierarchy of types and char being essentially an integer but on explicitly specifying char, the new function is executed.
For more information interchangeable use of char and int, see Java - char, int conversions