开发者

Java Newbie having trouble understanding some `new` syntax

I'm a relative newbie to Java. I program in other languages and I use Java mainly when I need to use third party libraries that are only available as Java. As such, I have only very basic understanding of the language. But usually this is enough to get my business done.

Today I ran into a problem that is so basic I'm having trouble Googling it or looking it up. In the following code snipit I don't understand the new GSRadContext line at all:

GSRBristowCampbellStrategy algo = new GSRBristowCampbellStrategy();
RadData rd = new RadData();

... 

GSRadContext gsr = new GSRadContext( (IAGSRadStrategy) algo);
gsr.evaluate(rd);

In my limited Java experience I've never seen this type of syntax inside of a new object() call before. Can you explain to me what's going on with the (IAGSRadStrategy) bit?

Thanks for contributing to my educatio开发者_JAVA技巧n.


This bit:

(IAGSRadStrategy) algo

is completely separate from the constructor. If it helps, you can think of the second bit of code as:

IAGSRadStrategy tmp = (IAGSRadStrategy) algo;
GSRadContext gsr = new GSRadContext(tmp);
gsr.evaluate(rd);

It's just a casting expression. Without knowing the type hierarchy involved, it's tricky to know exactly why it's being used here, but normally a cast is to basically tell the compiler, "You only know about this expression as Foo, but I know it's a Bar... so please check it for me at execution time, and then treat the value as a Bar for the result of this expression."


algo, a reference to a GSRBristowCampbellStrategy is being cast as a IAGSRadStrategy and passed to the GSRadContext constructor.

Gratuitous Wikipedia link:

Type Conversion


This GSRadContext class has a constructor which takes a IAGSRadStrategy type of object as argument. The algo instance is a sub-type of IAGSRadStrategy, that's why it is being type-casted into that type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜