Friday, January 30, 2009

Implementing an Interface  

0 comments

A Sample Interface, Relatable


Consider an interface that defines how to compare the size of objects. 

public interface Relatable {
 
  // this (object calling isLargerThan) and
  // other must be instances of the same class
  // returns 1, 0, -1 if this is greater

  // than, equal to, or less than other

  public int isLargerThan(Relatable other);

   

Implementing the Relatable Interface
Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable. 
public class RectanglePlus implements Relatable {
  public int width = 0;
  public int height = 0;
  public Point origin;

  // four constructors
  public RectanglePlus() {
 origin = new Point(0, 0);
  }
  public RectanglePlus(Point p) {
 origin = p;
  }
  public RectanglePlus(int w, int h) {
 origin = new Point(0, 0);
 width = w;
 height = h;
  }
  public RectanglePlus(Point p, int w, int h) {
 origin = p;
 width = w;
 height = h;
  }

  // a method for moving the rectangle
  public void move(int x, int y) {
 origin.x = x;
 origin.y = y;
  }

  // a method for computing the area of the rectangle
  public int getArea() {
 return width * height;
  }
   
  // a method to implement Relatable
  public int isLargerThan(Relatable other) {
  RectanglePlus otherRect = (RectanglePlus)other;
  if (this.getArea() < otherRect.getArea())
  return -1;
  else if (this.getArea() > otherRect.getArea())
  return 1;
  else
  return 0;  
  }
}
Because RectanglePlus implements Relatable, the size of any two RectanglePlus objects can be compared.

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories



0 comments: to “ Implementing an Interface

Extension Factory Builder