I have an abstract class, MyShape, and want to derive a few classes from it - say MyLine, MyRect, and MyOval. MyShape looks a little like this:
Here is sample code for a SIMPLE MyLine object:
Here are my questions: 1. First and foremost, is this designed correctly? Originally I had a ton of set/get methods, but I read that I don't need them since inter-class variable access was allowed. 2. What 4 variables do I use for drawLine? I know I need startX, startY, endX, and endY, and this works if I use get() methods in my super class, but I don't understand how to access these variables without them? Shouldn't an instance of the MyLine class (because it extends the MyShape class) automatically have those variables as part of its definition? How do I set/get those variables? 3. Should the height and width variables be defined within another sub-abstract class for shapes that have those dimensions? Or should I leave them where they are and just ignore them for the ONE MyLine class the is derived from MyShape?
Thank you all! I thought I understood classes, but without the book's answers right here, I suddenly don't seem to know so much.
-nothing important to say, but learnin' plenty-
Some answers. If you declare the variables as "private" (as you have done here), then the sub-classes can't access them directly. You have to provide getXXX() and setXXX() methods. Alternately you could declare them to be "protected" and then the sub-classes can access them directly by name. The classes become more tightly coupled since you can no longer rename the instance variables or change the implementation of the "MyShape" class without affecting every sub-class. As for question #2, if you leave startX, startY, etc. as "private", then you need to provide accessor methods and the "drawLine()" method will have to call "getStartX()", "getStartY()", etc. to acess them. If you redeclare them as "protected", then you simply pass in "startX", "startY", etc. As for question #3, you could create two abstract classes, "MyShape" and "MyShapeXXX". The former would have only startX, startY, endX, and endY. The latter would extend "MyShape" and add "height" and "width". The *real* classes (MyLine, MyCircle, etc.) could extend either "MyShape" or "MyShapeXXX" as appropriate. You are starting to think like an OO developer ... If you want to *force* all subclasses to override the "draw(Graphics gg)" method, declare it as "public void abstract draw(Graphics gg);"