How to call overload method in java

public class OverLoad {

    void method(Integer i){
        System.out.println("Integer "+i);
    }
    void method(int i){
        System.out.println("in "+i);
    }
    public static void main(String a[]){
        OverLoad m= new OverLoad();
        m.method(2); //it calls method(int i) why?    
    }
}

If I call m.method(3), it will call the int method, why? If I call m.method((Integer)3), then it will call the Integer method.

By default, it goes into a primitive data type

+4
source share
2 answers

By default, it goes into a primitive data type

Well yes, because this is the exact type of argument. The literal type 2is int, rather than Integer( JLS 3.10.1 ). It is converted to Integerthrough box conversion ( JLS 5.1.7 ), but this will only happen if it is really necessary.

Overloading in Java takes place in three stages: JLS 12.15.2 :

(§15.12.2.2) arity. - , .

, m.method(2) method(int) , .

+8

, 2 - Integer.

, ( int).

, (Integer)3, int 3 Integer.

+6

Source: https://habr.com/ru/post/1622873/


All Articles