Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 education.

like image 861
JD Long Avatar asked May 22 '26 00:05

JD Long


1 Answers

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."

like image 149
Jon Skeet Avatar answered May 24 '26 12:05

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!