The paintComponent() method of a JComponent gives you a graphics context of type Graphics that you can use for drawing on the component. In fact, the graphics context actually belongs to the sub-class Graphics2D (in Java version 1.2 and later), and can be type-cast to gain access to the advanced Graphics2D drawing methods.
Example code he uses:
I have read this paragraph and the surrounding paragraphs several times, and I can't figure out why you would have to type-cast to Graphics2D if it already belongs to Graphics2D. What am I missing here?
The class Graphics2D is a subclass of Graphics that adds many methods. Unfortunately, you can't call those methods through a variable of type "Graphics," simply because they're not part of that class. The compiler doesn't understand what the real type of the object is unless you tell it, and that cast is basically the way to tell the compiler "even though you think this object is a Graphics object, I actually know it's a Graphics2D object, so you should let me call the methods of that class on this object."
Whenever you have a variable whose type is some kind of object, imagine that the object is a dog and the variable is a leash. The variable (leash) is a way to hold on to the object (dog), but it's not the object (dog) itself.
Now, if you think about it, if you have a leash, you know you have some kind of Animal, but you don't really know what kind. You can do Animal stuff via the leash -- i.e., you can pull, and that's about it. If you want to do anything beyond pulling, you have to acknowledge that it's not just a generic Animal, and treat it like some specific kind of Animal (a Dog, for example).
If you imagine yourself deaf and blind, holding some kind of Animal on a leash, that's basically the situation the Java compiler is in: it honestly doesn't know what kind of animal is out there. Now, somebody can walk the dog over to you so you can pet it and feel that, in fact, it's a Dog, and now you can scratch behinds its ears and play frisbee and other Dog stuff. That other person has told you "here, this is a Dog you're holding on to." That is exactly what a cast is.
A cast of a reference variable (i.e., a variable that refers to an object) never changes the object -- it only changes how you can treat the object by providing additional information.
Ken Austin wrote:
But what I was getting at in my original question was the author seems to be saying "since the type is already dog, we can type-cast it to dog."
Well, that is what he's saying. He's saying that you have a Graphics variable pointing to a Graphics2D object; since it's a Graphics2D object, we can cast it and assign it to a Graphics2D variable, and then you can call all the methods of Graphics2D which, without the cast, would not have been accessible.
He's saying "Since we have a dog rather than an alligator on our leash, we can play Frisbee -- we just have to tell the compiler."