Tuesday, January 03, 2006

Overloading in Tiger

I was confused with how overloading in J2SE 5.0 works, so I compiled a little example to show. Initially, I thought the code will refuse to compile but I was proven wrong. It does compile and there is some precedence to which method that will be invoked.
public class Overload {
    public static void main(String[] args) {
        Overload m = new Overload();
        short s = 0;
        m.foo(s);
    }
    
    //Direct primitive type match will take precedence
    private void foo(short l){
        System.out.println("short"); 
    }

    //Primitive type promotion will take precedence over Autoboxing
    private void foo(long l){
        System.out.println("long");
    }
    
    //Autoboxing will only happen when primitive or promotion not available
    private void foo(Short l){
        System.out.println("Short");
    }
}

No comments:

Post a Comment