The Java Program: NonOO.java

  1 // NonOO.java -- illustrate type analysis versus OO
  2 
  3 class Point {
  4    protected float x,y;
  5    Point (float x, float y) { this.x=x; this.y=y; }
  6    void move (float dx, float dy) { x += dx; y += dy; }
  7 }
  8 
  9 class Rectangle extends Point {
 10    protected float height, width;
 11    Rectangle (float x, float y, float h, float w) {
 12       super (x,y); height=h; width=w;
 13    }
 14 }
 15 
 16 class Circle extends Point {
 17    protected float radius;
 18    Circle (float x, float y, float r) {
 19       super (x,y); radius=r;
 20    }
 21 }
 22 
 23 class NonOO {
 24 
 25    static void print (Point p) {
 26       if (p instanceof Rectangle) {
 27          final Rectangle r = (Rectangle) p;
 28          System.out.println ("("+r.x+","+r.y+";h="+
 29                              r.height+",w="+r.width+")");
 30       } else if (p instanceof Circle) {
 31          final Circle c = (Circle) p;
 32          System.out.println ("("+c.x+","+c.y+";r="+c.radius+")");
 33       } else {
 34          System.out.println ("("+p.x+","+p.y+")");
 35       }
 36    }
 37 
 38    public static void main (String [] args) {
 39       final Point p = new Point (2.3f, 4.5f);
 40       final Rectangle r = new Rectangle (2.3f, 4.5f, 45.1f, 89.1f);
 41       final Circle c = new Circle (2.3f, 4.5f, 0.3f);
 42       final Point [] list = new Point [] {p, r, c};
 43       for (Point q: list) q.move (0.1f, 0.1f);  // inheritance
 44       for (Point q: list) print (q);            // subclass polymorphism
 45    }
 46 }