Write a Rectangle class which has data members, height and width. The class shou
ID: 3560749 • Letter: W
Question
Write a Rectangle class which has data members, height and width. The class should have methods getHeight, getWidth and getArea. Two rectangles are equal if their areas are the same. Write the class using equals() method.
Write a main function, which creates two instances of rectangle and checks if the two rectangles are equal.
For e.g
Rectangle r1 = new Rectangle(3,5)
Rectangle r2 = new Rectangle(3,5)
System.out.println(r1.equals(r2));
Your program should not throw error for the below usage:
Rectangle r1 = new Rectangle(3,5);
String s =
Explanation / Answer
import java.util.*;
public class Rectangle
{
double height,width;
double area;
Scanner sc=new Scanner(System.in);
Rectangle()
{
getHeight();
//getHeigth()
getWidth();
getArea();
}
Rectangle(double height,double width)
{
this.height=height;
this.width=width;
this.area=height*width;
}
public void getHeight()
{
System.out.println("Enter height");
height=sc.nextDouble();
}
public void getWidth()
{
System.out.println("Enter width");
width=sc.nextDouble();
}
public void getArea()
{
System.out.println("Enter area");
area=height*width;
}
boolean equal(Rectangle r)
{
if(this.area==r.area)
return true;
else
return false;
}
public static void main(String args[])
{
Rectangle r1 = new Rectangle(3,5);
Rectangle r2 = new Rectangle(3,5);
if(r1.equals(r2))
System.out.println("Both are equal");
else
System.out.println("Both are not equal");
//Your program should not throw error for the below usage:
//Rectangle r1 = new Rectangle(3,5);
String s ="Hello";
System.out.println("For equating string and rectangle="+r1.equals(s));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.