CS112

Introduction to Object-Oriented Programming

Section: 2

Quiz No: 3

Date: 04.03.08

Question:

Define a rectangle class with length, witdh, coordinates (x,y). Then write the following methods:

  1. Two constructors: default and user defined.
  2. move method that moves rectangle in x and y directions.
  3. write two get methods which require some competition.
  4. write main method to test these by using array of rectangles.

 

Answer:

 

 

 

public class Rectangle {

      private int length, width, coorX,coorY;

      public Rectangle()

      {

            length=1;

            width=1;

            coorX=0;

            coorY=0;

      }

      public Rectangle(int length,int width, int coorX,int coorY)

      {

            this.length=length;

            this.width=width;

            this.coorX=coorX;

            this.coorY=coorY;

      }

      public void move(int x,int y)

      {

            coorX+=x;

            coorY+=y;

      }

      public int getPerimeter()

      {

            return 2*(length+width);

      }

      public int getArea()

      {

            return length*width;

      }

      public String toString()

      {

            return "Rectangle with length:"+length+" width:"+width+" coordinates:("+coorX+","+coorY+")";

      }

      /**

       * @param args

       */

      public static void main(String[] args) {

            // TODO Auto-generated method stub

            Rectangle[] rectList=new Rectangle[2];

            rectList[0]=new Rectangle();

            rectList[1]=new Rectangle(2,3,1,4);

            System.out.println(rectList[0]);

            System.out.println(rectList[1]);

      }

 

}