[JAVA] Overload method with Int and Integer arguments

-AutoBoxing was introduced from JDK1.5. For example, it automatically converts int and Integer. The same is true for method calls. You can call the int argument method using an Integer, and vice versa. It's quite convenient.

・ Then, the problem. -What happens if the arguments are defined as int and Integer in the method with the same name? -Are there any compilation errors? ・ If not, how can they be called?

・ Write down the conclusions obtained -Methods with the same name can be defined with int and Integer arguments, respectively. ⇒ That is, it can be overloaded ・ On the caller side, when calling with int or Integer, they are properly called. -Even if either method is deleted, it can be called and the remaining method is called.

Tips0005.java


package jp.avaj.lib.algo;

import jp.avaj.lib.test.L;

public class Tips0005 {
  public static void main(String[] args) {

    //Call method0 with int
    method0(1);

    //Call method0 with Integer
    method0(new Integer(10));

    //Call method1 with int
    method1(1);

    //Call method1 with Integer
    method1(new Integer(10));

    //Up to this point, the result is natural..


    //Call method2 with int
    method2(1);

    //Call method2 with Integer
    method2(new Integer(10));

  }
  /**method of int argument*/
  private static void method0(int v) {
    L.p("intMethod0:"+v);
  }
  /**Integer argument method*/
  private static void method1(Integer v) {
    L.p("integerMethod1:"+v);
  }

  /**method of int argument*/
  private static void method2(int v) {
    L.p("intMethod2:"+v);
  }
  /**Integer argument method*/
  private static void method2(Integer v) {
    L.p("integerMethod2:"+v);
  }

If you look at the results, they are properly called. Speaking of course, it is natural, but confirmation that it is natural.

But rather, is it a problem that both can be defined? Perhaps I didn't realize that I defined both, and there was no bug.

Execution result


intMethod0:1
intMethod0:10
integerMethod1:1
integerMethod1:10
intMethod2:1
integerMethod2:10

Recommended Posts

Overload method with Int and Integer arguments
Integer check method with ruby
Overload when method arguments are inherited / implemented
Equal value judgment of Integer and int
Difference between int and Integer in Java
[Ruby] Arguments with keywords and default values of arguments
Compare Integer with ==
variable and method
About call timing and arguments of addToBackStack method
Check method call arguments in blocks with RSpec
Formal and actual arguments
[Java] Arguments and parameters
[Java] Overload and override
[Ruby] Questions and verification about the number of method arguments
Kotlin post- and pre-increment and operator overload (comparison with C, Java, C ++)