This site requires JavaScript, please enable it in your browser!
Greenfoot back
darkmist255
darkmist255 wrote ...

2011/11/22

Incompatible types

darkmist255 darkmist255

2011/11/22

#
Okay... So I guess I must still not get references entirely, since I'm having this problem. When I do the following code:
        PlayerPaddle collidedBlue = getOneIntersectingObject(PlayerPaddle.class);
        if (collidedBlue != null)
        {
            setRotation(0);
        }
I get the error "incompatible types" and it doesn't like (PlayerPaddle.class). I find this strange since this exact code with a different class and variable names works...
darkmist255 darkmist255

2011/11/22

#
Ookayy... I changed it to
PlayerPaddle collidedBlue = (PlayerPaddle)getOneIntersectingObject(PlayerPaddle.class);
and it worked? Why does that (PlayerPaddle) matter?
kiarocks kiarocks

2011/11/22

#
You are casting the type PlayerPaddle to the list of objects.
mjrb4 mjrb4

2011/11/22

#
The (PlayerPaddle) bit is called a cast. If you look at the return type for getOneIntersectingObject(), it's Actor. Now the compiler has no way of knowing that actually, because of the parameters you've specified, that method will always return a PlayerPaddle object (which is a more specific type of Actor since it inherits from Actor.) The cast is essentially you saying "trust me, I know this method will always return a PlayerPaddle so treat it as such." If you violate that trust by putting another type of actor that isn't a PlayerPaddle, you'll get an exception at runtime telling you so. As a side note, it is possible in Java to use something called generics that would mean you didn't have to use the cast each time, but we don't use it because it makes the documentation for the method and what's happening underneath a lot more complicated to understand.
darkmist255 darkmist255

2011/11/23

#
Thanks :D.
You need to login to post a reply.