style on calling child method

i'm making a 'paint' application. and i want be able to draw many different shapes (rects, ovals, stars, etc)

i have a base class called ShapeTool which contains a lot of functionality for handling mouse events, calculating x, y, width, height etc.

all the instanciated tools (RectTool, OvalTool etc) inherit from ShapeTool and only contain a method draw() to draw themselves.

this draw method is called from parent class (ShapeTool) which of course needs a reference to the child

my question is if i should have :

(A) protected x, y, width, height, Graphics g fields in ShapeTool so the child's draw implementation will be like

public draw(){

g.drawOval(x, y, width, height);

}

because the child will be able to see the protected fields

or

(B) have the fields private and pass them as parameters from the ShapeTool so the child's draw implementation will be like

public draw(int x, int y, int width, int height, Graphics g){

g.drawOval(x, y, width, height);

}

tnx

[1066 byte] By [ioannisca] at [2007-9-28 5:44:46]
# 1

As you note yourself, it is a question of style. Both a) and B) are perfectly good solutions.

Personally I would make x and y private if no subclass should be able to modify them. If a subclass only needs to read the variable, use getter-methods. This eliminates the possibility of a subclass modifying those variable by accident (e.g. a non-declared local variable called x).

Søren

soren_baka at 2007-7-9 16:55:35 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
I would use the B) way, becouse it makes it more easy to modify the code style afterwards. So you could use an other GraphicsObject (maybe a buffer image (jpeg output?) or using a XOR-mode view on an other panel) to draw on.
JD_dimaa at 2007-7-9 16:55:35 > top of Java-index,Other Topics,Patterns & OO Design...