Construct a class Rectangle. Provide a constructor to construct a rectangle with a
given width and height, member functions get_perimeter and get_area that compute the
perimeter and area, and overload method to resize the rectangle. For example r*factor
(double factor) resizes the rectangle by multiplying the width and height by the given
factor.
SOLUTION
package com.company;
class Rectangle
{
double width;
double length;
//constructoer to set the length and width
Rectangle()
{
this.width = 8;
this.length = 12;
}
//A method to get perimeter
double perimeter()
{
return (width*2)+(length*2);
}
//A method to get area
double area()
{
return (width*length);
}
//overload the constructor now
Rectangle(int factor)
{
this.width = width * factor;
this.length = length * factor;
}
}
public class Main{
public static void main(String[] args) {
//create an object of the parameterless constructor
Rectangle r = new Rectangle();
System.out.println("The perimeter of the Rectangle is "+r.perimeter());
System.out.println("The area of the Rectangle is "+r.area());
Rectangle r2 = new Rectangle(2);
System.out.println("The perimeter of the Rectangle for r2 is "+r.perimeter());
System.out.println("The area of the Rectangle for r2 is "+r.area());
}
}
Comments
Leave a comment