chillworld
chillworld

Reputation: 4277

Method overloading with dynamic casting

I'm looking into the method overloading of Java.
Take the next sample :

public static void main(String[] args) {
    Object object = "some String";
    System.out.println(object.getClass().getSimpleName());
    System.out.println(belongsToAllowedTypes(object.getClass().cast(object)));
    String string = "another String";
    System.out.println(belongsToAllowedTypes(string));
}

public static boolean belongsToAllowedTypes(Object value) {
    return false;
}

public static boolean belongsToAllowedTypes(String value) {
    return true;
}

I'm expecting an output like :

String
True
True

Just because I get the String class and cast the Object to that class before I invoke the method.
But no luck, I'm getting false in the second println.
So it's still processed as an Object (however the class is String)

If I change it to :

System.out.println(belongsToAllowedTypes(String.class.cast(object)));

I do get a True.

Can anyone explain this behavior?

Upvotes: 0

Views: 250

Answers (1)

Henry
Henry

Reputation: 43728

The method to call is determined at compile time. So with object having type Object the type of

object.getClass().cast(object))

at compile time is an Object independent of the dynamic content of object.

Upvotes: 3

Related Questions