Punit Mehta
Punit Mehta

Reputation: 11

How draw method of Graphics2D works in JAVA?

When I saw the source code of Graphics2D.java , I came to know that draw() method is declared abstract over there. Then how can it be useful ? .. I mean Where is the implementation of draw method ?? Being abstract method , how it actually draws the objects ..!!!! ??

Upvotes: 0

Views: 508

Answers (1)

npinti
npinti

Reputation: 52185

The Graphics2D is an abstract class. As stated here:

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

So technically, it never needs to draw anything itself. On the other hand, when the method was declared as abstract the creators of this class wanted to leave the implementation details of this method to whoever was extending it.

So basically you can't do this:

Graphics2D g = new Graphics2D();
g.draw();

But you can do this:

public class MyClass extends Graphics2D
{
    ....
    @Override 
    void draw(Shape s)
    {
        //Draw your shape here in what ever way you want.  
    }
}

Then you can do this:

Graphics2D g = new MyClass();
g.draw(myShape);

Upvotes: 2

Related Questions