Java. Overload method

For example, I have this class:

public class Col {

static void test(int a)
    {
        System.out.println("int");
    }
    public static void main(String args[])
    {
        Col.test(12);  //1

        Col.test((byte)12); //2

        Col.test((long)100); //3

    }
}

and now I'm wondering how the algorithm works on this code. I think these steps are:

1 line - all the correct calling methods with int param, perfect.

2 method of calling a string with byte param ... oooops. what? Java trying to expand byte to int? It's true?

3 method of calling a string with a long parameter ... again ooops. what? java cannot convert long to int, because there is a loss of precision. try it out? And the result is an Exception.

How do I add this:

 public static void test(Object a)
    {
        System.out.println("Object");
    }

and if the call:

Col.test((long)100);

everything is correct, without exception, so what is the relationship between the primitive type long and Object?

+5
source share
6 answers

, byte int, long int (- ).

autoboxing, long ( ) long ( ).

, test :

public static void test(Object a)
{
    System.out.println(a.getClass());
}

class java.lang.Long.

+7

. , - (, long) (java.lang.Long ).

, , . :

static void test(int a){}
static void test(Object a){}

test((long) 100). , JVM long int . JVM ( 1.5+) long long (autoboxing) test(Long.valueOf((long) 100)) .

+4

, . , (Object a). , Col.test( Integer (12)), (Object a). ,

+3
public static void test(Object obj) {
      if (obj instanceof Integer) {
          System.out.println("Integer");
      } else if (obj instanceof Double) {
          System.out.println("Double");
      } else if (obj instanceof Float) {
          System.out.println("Float");
      } else if (obj instanceof Long) {
          System.out.println("Long");
      } 
  }
+2

All java primitives have corresponding box types, which are valid classes. In your example, long has the corresponding class Long. This class extends from Object.

What you experienced is boxing and unboxing.

+2
source

This is a feature introduced in Java 5. It is called Autoboxing. In this, the primitive type is converted to Object (in your case, long to Long). More about Autoboxing see. This link .

+2
source

All Articles