This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
As I was reviewing an example used in the Head First Java book (second edition), bottom of page 367, I went to the API to look up a method, setPaint(), used in the example and noticed that all of the methods in the class (java.awt.Graphics2D) that setPaint() belongs to are abstract.
My question is, how do these methods work if they are all abstract? In the example in the book, there is this code:
FYI, the setPaint() method takes a Paint argument, and the example in the book creates a GradientPaint object (represented by the gradient variable), a subclass of the Paint class, so it is polymorphically OK for setPaint() method to take the gradient variable argument. This makes sense to me.
What I don't understand is why we're using the Graphics2D setPaint() method if it is abstract? An abstract method has no code implementation, which would mean the abstract setPaint() method in the Graphics2D class has no code implementation, which makes me wonder how it can set the Graphics2D class' Paint attribute in the first place? If we wanted to set a Paint attribute, wouldn't we have to create a subclass of Graphics2D that provides method implementation code for setPaint(), thereby providing a way to set a Paint attribute? Is there some unique functionality going on in this class (and other similar classes) that I'm not aware of?
It sounds like you haven't understood yet exactly how polymorphism works.
The implementation of the abstract method is in a subclass that you don't see. Consider this Shape class and its subclass Circle:
Now you can create a variable of type Shape that refers to a Circle object, and you can call draw() on s:
Note that you can call draw() on s, even though s is a Shape and draw() is abstract in class Shape.
This works the same way in your example. The Graphics2D object that you have really refers to an instance of a non-abstract subclass of Graphics2D. You don't need to know exactly what that class is - you only need to know that all methods of class Graphics2D can be called on it.
If you'd really like to know what kind of object g2d refers to, you can print out its class name like this:
Hi, I have not that book but in your code example there is an Object g which is casted to Graphics2D. So if g is a Subclass of Graphics2D I think the Graphics2D-Methods can be used. Note the g-Object is not a Graphics2D-Object which has the abstract Methods. It is not possible to instanciate Objects of abstract classes. If you create an Object all Methods are implemented. g has the implemented Methods which are abstract in Graphics2D and the Methods can be called on this Object.