Now, we present the complete example by adding two other movable objects: Movable Circle (mCircle) and Movalbe Triangle (mTriangle). You will see the OOP make the code very simple. We will reuse the parent object's varibles and methods in variety situation.
We design a mCircle child object from mRectangle object. You can see how simple it is! The constructor call the mRectangle's. Only redefine the drawing method!
public class mCircle extends mRectangle { public mCircle(int _x, int _y, int _w, int _h) { /* call mRectangle's constructor */ super(_x, _y, _w, _h); } public void paint(Graphics g) { /* draw a circle */ g.setColor(color); g.fillOval(x, y, w, h); } }
Add another movable object mTriangle (piece of cake!).
public class mTriangle extends mRectangle { public mTriangle(int _x, int _y, int _w, int _h) { /* call mRectangle's constructor */ super(_x, _y, _w, _h); } public void paint(Graphics g) { /* draw triangle */ int xx[] = { x, x+w, x+w/2}; int yy[] = { y+h, y+h, y}; g.setColor(color); g.fillPolygon(xx, yy, 3); } }
Class Hierarchy: Applet --- Test mPoint --- mRectangle -+- mCircle | +- mTriangle
JAVA Source Code
1. Test.java (Main Program)
2. mPoint.java (Movable Point)
3. mRectangle.java (Movable Rectangle)
4. mCircle.java (Movable Circle)
5. mTriangle.java (Movable Triangle)