VortixDev VortixDev - 1 year ago 75
Java Question

Extending Graphics2D - casting causes exception

I'm trying to improve my Java ability by creating a 2D game. I've succeeded in creating a basic game and am now going back over the things I did to see what I can improve, and I'm restructuring the code a little. I previously had a drawObject method built in which draws a GameObject (another class I created for my game) which had to have the Graphics2D object passed to it, however now I'm attempting to extend Graphics2D and build all of the "draw(X)" methods I've created into that extending class so that I don't have to pass the Graphics2D object about, however I'm having difficulty.

I start the class as follows:

public abstract class GameGraphics extends Graphics2D
. No errors appear in Eclipse, so I run it however that is when I get an error upon rendering stating that
cannot be cast to an instance of my class which extends it.

The error appears on the following line:
GameGraphics graphics = (GameGraphics) strategy.getDrawGraphics();

Despite the fact that I need to use a specific method from Graphics2D, I attempted to make it extend Graphics instead to see what would happen. I modified calls to Graphics2D functions and found no errors, however when I ran it I got the exact same error. Even the SunGraphics2D part was the same.

It seems to me the obvious fix would be to have the class simply contain an instance of Graphics2D rather than extend Graphics2D, however I would much prefer extending if it is possible.

Any help would be appreciated!

Answer Source

The problem is that on this line:

GameGraphics graphics = (GameGraphics) strategy.getDrawGraphics();

The Graphics object obtained from your strategy object is not a GameGraphics object, and casting it as such does not make it so. Casting would only work if you could modify strategy so that it in fact produces a GameGraphics object, although I'm not sure that you want to do this or can do this (at least not easily). As Kayaman states -- use composition to get what you want, not inheritance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download