• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

在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));
	}
}

运行结果

posted on 2022-04-12 20:02  王陈锋  阅读(35)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3