Emir
Emir

Reputation: 772

Extending Graphics2D class without implementing all methods

I have a class named MyClass and I want this class to extend Graphics2D (in java.awt). However when I type public class MyClass extends Graphics2D { .... } I have to add the unimplemented methods draw, drawImage, addRenderingHints, etc. because Eclipse shows this error and it won't compile.

This is where the question comes to my mind: I just want to use draw, setBackground and other few methods of Graphics2D, I don't want the rest of the code coming with other unimplemented methods which are mandatory.

Is there a way to avoid this? Because I'm extremely clean and simple when it comes to code and I don't want other 100 lines of code which I don't even use.

What are your suggestions?

Upvotes: 5

Views: 2664

Answers (2)

Jake Roussel
Jake Roussel

Reputation: 641

You could have it extend Graphics, and whenever you need a Graphics2D, just cast.

Graphics g = this.create(); Graphics2D g2d = (Graphics2D) g;

You'd need to make a Graphics variable within however, as you cannot cast this.

So for "setBackground":

public void setBackground(Image img) {
    g2d.setBackground(img);
}

Really, though, no matter what you do, it's going to be messy. I'm not even sure if you can do the this.create() thing without bad stuff happening, so keep that in mind.

Upvotes: 3

SJuan76
SJuan76

Reputation: 24895

See http://download.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html

Graphics2D is an abstract class, lots of methods are not abstract and all of them must be defined in order to get a subclass that can be instantiated.

If you want to try, you could try extending some class that implements Graphics2D. But then, if you are not careful you will be risking that your implementation of the methods that you want may not be coherent with the methods that you do not override...

Upvotes: 3

Related Questions