Question

I cant figure out how the int 7 is consider as object in below example.

The sifer(7) is consider to be method sifer(Object o). I am not able to get it how this happened. In one of my java reference book it says Int can be boxed to an Integer and then "widened" to an object. I am not sure what that means.

 >> Class A 
class A { }     

 >> Class B 

class B extends A { }   
 >> Class ComingThru  

public class ComingThru {  
   static String s ="-";    
static void sifer(A[] ...a2)  
{  
    s = s + "1";  
}

static void sifer(B[] b1)  
{
    s += "3";  
}
static void sifer(Object o)   
{
    s += "4";  
}      

   public static void main(String[] args)   {
        // TODO Auto-generated method stub

    A[] aa= new A[2];  
    B[] ba = new B[2];  

    //sifer(aa);  
    //sifer(ba);  
    sifer(7);
    System.out.println(s);  


}  

}

Was it helpful?

Solution

Since there is no sifer(int) method, the compiler will try to find the "closest match". In this case, the other 2 sifer methods take arrays as parameters, which an int clearly isn't.

The last method, sifer(Object) can be applied to any objects, including an Integer so that's the method that is used for sifer(7).

The reality is a little more complex, and the JVM will look for a matching mathod in the following order:

  • an identity conversion
    • in your case: sifer(int) but there is no such method
  • a widening primitive conversion
    • in your case: sifer(long) for example, but there is no such method
  • a widening reference conversion
    • in your case: not applicable, int is not an object
  • a boxing conversion optionally followed by widening reference conversion
    • in your case that's what's happening: int is boxed to Integer which is widened to Object
  • an unboxing conversion optionally followed by a widening primitive conversion
    • in your case: not applicable

OTHER TIPS

1. Above code provides an classic example of Method Overloading, along with AutoBoxing and Auto-UnBoxing which came by Java 1.5, cause manual Boxing and Unboxing was a pain.

2. The sifer(A[]... a2) and sifer(B[] b1) both accepts Array type Arguments in its parameter, which no way matches int. So now we are left only with sifer(Object o).

3. Now the int will be converted into Wrapper Object Integer Automatically.

You can verify it by doing this in snifer(Object o) method.

    o.getClass().getName();

See this link for further details:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

7 will be auto boxed to Integer which is an Object

Also See

Steps as below-

  1. The int (7) was boxed to a Integer.
  2. The Integer reference was widened to an Object (since Integer extends Object).
  3. The sifer() method got an Object reference that actually refers to a Integer object.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top