在Rectangle中,重写equals方法,使得两个Rectangle对象比较时,width,height两个值相等则认为这两个Rectangle对象相等
Rectangle类代码
public class Rectangle
extends GeometricObject
{
private double width;
private double height;
public Rectangle() {}
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public Rectangle(double width, double height, String color, boolean filled)
{
this.width = width;
this.height = height;
setColor(color);
setFilled(filled);
}
public double getWidth()
{
return this.width;
}
public void setWidth(double width)
{
this.width = width;
}
public double getHeight()
{
return this.height;
}
public void setHeight(double height)
{
this.height = height;
}
public double getArea()
{
return this.width * this.height;
}
public double getPerimeter()
{
return 2.0D * (this.width + this.height);
}
@Override
public boolean equals(Object r1)
{
if(r1 instanceof Rectangle) {
return (this.width ==((Rectangle)r1).width)&&(this.height==((Rectangle)r1).height);
}
else {
return false;
}
}
}
其中的equals方法重写
@Override
public boolean equals(Object r1)
{
if(r1 instanceof Rectangle) {
return (this.width ==((Rectangle)r1).width)&&(this.height==((Rectangle)r1).height);
}
else {
return false;
}
}
亦或着
@Override
public boolean equals(Object r1)
{
if(r1 instanceof Rectangle) {
Rectangle r=(Rectangle)r1;
return this.width ==r.width&&this.height==r.height;
}
else {
return false;
}
}
Main主类代码
public class Main{
public static void main(String[] args)
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
Rectangle r3=new Rectangle(3,6);
System.out.println("jieguo:"+r1.equals(r2));
System.out.println("jieguo:"+r1.equals(r3));
}
}