Difference between Graphics and Graphics2D?

I’m wondering the difference between doing the two:


Graphics g = image.getGraphics();

// and

Graphics2D g = (Graphics2D)image.getGraphics();

?

image.getGraphics() actually returns a Graphics2D object, although the return-type is Graphics.

Graphics2D is a subclass of Graphics. With Graphics2D you have more advanced features, so you might want to cast the returned object to it, to access these functions.

you get a graphics2d object all the time, if you cast it to a Graphics2D you simply tell the compiler that you know that you get a Graphics2D object and therefore can use all the methods supported by graphics2d.

So if you don’t need any graphics2d method its perfectly valid to also use a plain graphics object, the same methods will be called anyway.

lg Clemens

Is there any performance difference between using Graphics and Graphics2D? If Graphics2D is more complex and advanced, maybe it is also somehow accelerated or optimized?

The Graphics object (in this context) is a Graphics2D object in disguise. It’s the same object. No difference.