The Graphics class (java.awt.Graphics) is declared as an abstract class and is the superclass of class Graphics2D and DebugGraghics. The Graphics method .setColor() is also declared abstract, so I expect this method has no body and no 'behavior'-influencing function within the Graphics class. The .setColor() method is also not defined in the Graphics2D class; in fact, this method is not to be found in the Graphics2D class at all. Still, if I call the method (Graphic g; g.setColor(Color.red)), it actually works!!?? That would mean that the .setColor() method of the Graphics class does have a body (is defined) and has a function. Can someone tell me why/how this works? Thanks.
When you get an object whose type appears to be "Graphics", the actual class of that object will be some subclass of Graphics. Of course this subclass cannot be abstract, since you have an object of that subclass. So that subclass must have an implementation of setColor(Color). That's just how the "abstract" keyword works, it's not specific to Swing classes.
You're probably expecting that the subclass in question will be something whose documentation you can see in the API. But that isn't the case; Swing has its own internal classes for two reasons: first, there are different classes for different operating environments (Windows, Unix, etc), and second, there are different classes for different look-and-feels. You can find out the name of an object's class by calling its getClass() method, so why don't you try that on your "Graphics" object and see what you find out?
Thanks for the helpful reactions sofar. I know for sure that the 'g'-object in question appears to be an instance of the Graphics class, but is in fact a Graphics2D object. But the Graphics2D class is (in the API) also abstract, just like its superclass Graphics. So I'm still puzzled:
1. how can I have an object of an abstract class;
2. that uses a method (setColor) which - according to its API) - is an abstract method in the superclass Graphics (so has no body) and is not implemented in Graphics2D.
Call me thick, but I'm trying to understand how this works. Cheers!