What is the result of this Java kernel code?

public void getData(Object o[]) { System.out.println("In Side Array"); } public void getData(Object o) { System.out.println("In Side Object"); } public static void main(String[] args) { new JavaEx().getData(null); } 

Here it prints an array block, why, why doesn't it print an Object block?

+5
source share
4 answers

Both getData methods can handle the null argument. In this situation, Java tries to choose a method that handles a more specific type.

Now Object by definition a superclass of all Java classes, so in this situation, Object[] (which is also Object ) is a more specific type, and getData(Object o[]) is a more specific method. This is why Java chooses this method.

+4
source

According to JLS (Java Language Specification) for determining method signing time

  • The first phase performs overload resolution without allowing boxing conversion or decompression or using the arity invocation variable method. If at this stage no applicable method is detected, processing continues until the second phase.

  • The second phase performs overload resolution when resolving boxing and unpacking, but still eliminates the use of the arity variable by calling the method. If at this stage no applicable method is found, processing continues until the third phase.

  • The third stage allows you to combine overloading with the methods of the variable arity, boxing and unpacking.

In your example:

when you call the getData() method, passing the null argument, the compiler goes to the first phase and the found method signature, without executing any box.

Thus, the output is "In the side array"

+1
source

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

“If more than one member method is available and applicable to a method call, you must select it to provide a handle to send the runtime. The Java programming language uses the rule that the most specific method.

An unofficial intuition is that one method is more specific than another if any call processed by the first method can be passed to another without a compilation type error.

+1
source

Perhaps this will make a difference:

 public void getData(Object o[]) { System.out.println("In Side Array"); } public void getData(Object o) { System.out.println("In Side Object"); } public static void main(String[] args) { Object[] array = null; new JavaEx().getData(array); } 

In this implementation, "In Side Array" will also be printed, since an uninitialized array may be null . Therefore, it becomes apparent that the array method is being called.

-2
source

All Articles