Java Example | Java Tutorial | Java gtu


Write a class named Rectangle to represent a rectangle . It contains following members:

Data : Width (double) and Height (double) that specify the width and height of the rectangle.

Methods: 

  1. A no-arg constructor that creates a default rectangle.
  2. A Constructor that creates a rectangle with the specified width and height.
  3. A method named getArea() that returns the area of this rectangle.
  4. A method named getPerimeter() that returns the perimeter.

Program:-


package assignmentexamples;
public class Rectangle
{
   double width , height;
   Rectangle()
   {
      System.out.println("\n------|A Rectangle having width and height|------\n");
   }
   Rectangle(double a, double b)
   {
      width=a;
      height=b;
      System.out.println("Width of rectangle is :- \n "+ width);
      System.out.println("Height of rectangle is :- \n "+ height);
   }
   Double getArea()
   {
      return(width*height);
   }
   Double getPerimeter()
   {
      return(2*(width+height));
   }
   public static void main(String[] args)
   {
      Rectangle obj = new Rectangle();
      Rectangle obj1 = new Rectangle(2,3);
      System.out.println(" ");
      System.out.println("Area of Rectangle is:-\n"+obj1.getArea());
      System.out.println("Perimeter of Rectangle is:-\n"+obj1.getPerimeter());
   }
}



Output:-

Post a Comment

2 Comments