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?
4
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.
0
Graphics2D is also an abstract class. My understanding is that it is an object of a concrete child class of Graphics2D. We do not need to know the name of that class… only that it implements the abstract methods of its abstract parent/grandparent classes: Graphics2D and Graphics.
For example, the Graphics2D g object that is passed to paintComponent, for example, is not an object of type Graphics2D except in the inheritance context: the g is an object of type ??? which extends Graphics2D, so it is an object of type ???, which IS A Graphics2D, which IS A Graphics.
I am not an expert, but this is how I understand it.