You're viewing this page with a browser that doesn't understand the APPLET tag. If you were using a Java-enabled browser that understood the APPLET tag, you'd see Scrolling Text here.

In this example, we can see two rectangle moving on the screen. We will use this example to explain the Object Oriented Programming (OOP) in JAVA

Object Oriented Programming in JAVA

We define a Movable Point Object (mPoint) that has x, y as its location, dx, dy as its moving delta and color as its color attribute.

public class mPoint {
  int x, y;
  int dx = 1, dy = 1;
  Color color = Color.black;
  public mPoint(int _x, int _y) {
    /* initial location */
    x = _x;
    y = _y;
  }
  public void setDelta(int _dx, int _dy) {
    dx = _dx;
    dy = _dy;
  }
  public void setColor(Color _color) { color = _color;}
  ....

To move the object, we define a general method move. That will caculate the new location and draw the object.

  /* move object */
  public void move(Graphics g) {
    x += dx;    /* update location */
    y += dy;
    paint(g);   /* draw object on new location */
  }

We define a drawing method here but leave it blank. The child object can overwrite this method and redefine it.

  public void paint(Graphics g) {}

Now, we define a child object Movable Rectangle Object (mRectangle) that inherit the variables and methods from its parent Movable Point. The rectangle still need the width and height parameter. So we only add two varibles w, h in this object.

public class mRectangle extends mPoint {
  int w, h;
  public mRectangle(int _x, int _y, int _w, int _h) {
    /* call mPoint's constructor */
    super(_x, _y);
    /* initial w and h */
    w = _w;
    h = _h;
  }
  ...

We redefine the drawing method and actually draw a rectangle here.

  public void paint(Graphics g) {
    /* draw rectangle */
    g.setColor(color);
    g.fillRect(x, y, w, h);
  }

Now, we already define the movable object, you can click on the Test.java to see how to initialize the movable object and how to display and move it on the screen.

Class Hierarchy:
Applet --- Test
mPoint --- mRectangle

JAVA Source Code
1. Test.java (Main Program)
1. mPoint.java (Movable Point)
1. mRectangle.java (Movable Rectangle)