We saw many programs, where drawString() is called to print any message on the applet window area. But drawString() is an abstract method of Graphics class. I never saw any code, where drawString() is implemented. My question is, who implements the drawString()? If any one provides the implementation for this method either by extending Graphics class, how could we use drawString() in our applet , without accessing that particular class. Please clarify.
Whenever the paint method is called, an instance of a concrete subclass of Graphics that implements its abstract methods is sent to the method.
You can see it if you run this example.
[ February 28, 2007: Message edited by: Keith Lynn ]
posted 11 years ago
I can understand that sun.java2D.Graphics2D is the class that provides an implementation to the abstract method. But I'm a bit confused here. We neither instantiated any object of that concrete class nor we have a reference to one of its objects. So behind the scenes, how is drawString() of the concrete class is invoked. If my understanding is correct, since we have the reference of Graphics class in our paint method, it can invoke a method on its subclass. But for that don't we need to have an object to be available. Please let me know , if my understanding is correct.
I don't understand what you're saying, exactly. Your paint() method takes an argument of type "Graphics". When your paint() method is called, the JVM passes you an instance of some subclass of Graphics which implements all the abstract methods. You call the methods on this object.
The notion of abstract methods being implemented in subclasses is part of the idea of polymorphism. It sounds like you might not be clear on this concept. Try reading this entertaining story to help you firm up your understanding.