문제: toString(), equals() 구현하기

문제 설명

 package lang.object.test;

 public class RectangleMain {
      public static void main(String[] args) {

	       Rectangle rect1 = new Rectangle(100, 20);
         Rectangle rect2 = new Rectangle(100, 20);

         System.out.println(rect1);
         System.out.println(rect2);
         System.out.println(rect1 == rect2);
         System.out.println(rect1.equals(rect2));
     }
 }

실행 결과

  Rectangle{width=100, height=20}
  Rectangle{width=100, height=20}
  false
  true

정답 Rectangle 클래스

  package lang.object.test;
  public class Rectangle {

      private int width;
      private int height;
      
      public Rectangle(int width, int height) {
         this.width = width;
         this.height = height;
      }
      
      @Override
      public boolean equals(Object o) {
          if (this == o) return true;
          if (o == null || getClass() != o.getClass()) return false;
          Rectangle rectangle = (Rectangle) o;
          return width == rectangle.width && height == rectangle.height;
     }
     
     @Override
     public String toString() {
		     return "Rectangle{" +
						     "width=" + width +
									", height=" + height +
									'}';
     }
}