Search code examples
javajpanelabstract

How can I use Graphics - an abstract class


I was wondering how java.awt.Graphics works and so I went to the source code through NetBeans. I noticed that Graphics is an abstract class and all of the function I am using are abstract methods.

This made me think, how can I use Graphics?

I mean, Graphics is an abstract class and I am using an Graphics object within JPanel. How does it work? How can I use it, as an abstract class, without using a class that implements Graphics?


Solution

  • You can't use an instance of an abstract class directly. Abstract classes such as Graphics cannot be instantiated; only concrete subclasses can (Graphics has two, DebugGraphics and Graphics2D). In the JPanel case, the Graphics argument you get in paintComponent() is actually an instance of Graphics2D (you can check this by casting it). The Graphics2D class provides the implementation of the abstract methods in Graphics.