开发者

Use Method by Real Type

开发者 https://www.devze.com 2023-04-11 17:38 出处:网络
I learned that I can use the real type of a Object to define which Method is used开发者_运维技巧, such like this:

I learned that I can use the real type of a Object to define which Method is used开发者_运维技巧, such like this:

[...]
Object foo = new String("hello");
[...]
bla(foo);

void bla(String x){
}
void bla(Integer x){
}

Now it should take the bla(String x) method, but instead I get compiler error. I know why: because the type of foo is currently Object. I'm not sure if I do it currently right, but I understood it that way, that Java will choose the method by the real type (or specific type), so if I downcast it to Object, it will choose the String instead, if no Object Method is specified.

Or is the only way to determinate the type by if(foo instanceof xxx) in a method void bla(Object x)?

P.S.: dont get me wrong on this: I dont mean that I can overload methods, I mean that I want to choose the method based on the real type (not on the defined one)!


Now it should take the bla(String x) method, but instead i get compiler error.

Right. Which method is to be called at runtime, is chosen at compile-time, and the compiler can't (in general) tell which type foo will have in runtime.

...so if i downcast it to Object...

You can't "downcast to Object". You can downcast to a String though. And that's right, if you do

bla((String) foo);

it will invoke the bla that takes a String as argument (and throw a ClassCastException if foo is not a String).

Or is the only way to determinate the type by if(foo instanceof xxx) in a Method void bla(Object x)?

[...]

i mean that i want to choose the method based on the real type (not on the defined one)!

This is usually referred to as double or multiple dispatch, and is a feature not supported in Java.

Implement the visitor pattern if you really need this.


Btw, what you refer to as "defined type" and "real type" are usually referred to as static type and runtime type respectively. That is, Object is the static type of foo, while String is it's runtime type.


Yeah you have to use instanceof to get the realy type. bla( Object ) will always call the bla( Object o ) method.

Note: Chosing method based on the "real type" is only possible for class methods. object.method( ... ). Will chose the method based on the "real type" if one exists (and go up till Object).

Object foo = new String("hello");

// this will return "hello" although toString() 
// from Object only prints the reference
System.out.println( foo.toString() );
0

精彩评论

暂无评论...
验证码 换一张
取 消