Saturday, 11 August 2012

Create a class called Rectangle that stores width and height. display and get/set of the data

Create a class called Rectangle that stores width and height. display and
get/set of the data. its area. Test the code by creating an
implementation program


 import java.util.Scanner;


class Rectangle {
protected int width;
protected int height;
public Rectangle() {
    }
public Rectangle(int x, int y) {
        width = x;
        height = y;
    }
public Rectangle(int x) {
        width = x;
        height = 20;
    }


public int getWidth() {
        return width;
    }
public int getHeight() {
        return height;
    }
public void setWidth(int width) {
        this.width = width;
    }
public void setHeight(int height) {
        this.height = height;
    }


public void getData() {
        Scanner in = new Scanner(System.in);
System.out.println("Enter Width:");
        width = in.nextInt();
System.out.println("Enter Height:");
        height = in.nextInt();
    }
public void showData() {
System.out.println("Width is:" + width + "\nHeight is:" + height);
    }
public float getArea() {
        return (float) (height * width);
    }
public static void main(String args[]) {

Rectangle r = new Rectangle(20, 10);
        r.showData();
        System.out.println("Area is:" + r.getArea());
Rectangle r1 = new Rectangle();
r1.getData();
        r1.showData();
System.out.println("Area is:" + r1.getArea());
}

}


No comments:

Post a Comment