S.S.G
객체 비교와 equals()메소드 본문
int 타입의 width, height의 필드를 가지는 Rect 클래스를 작성하고, 두 Rect 객체의 width, height필드에 의해 구성되는 면적이 같으면 두 객체가 같은 것으로 판별하도록 equals()를 작성해보기.
class Rect {
int width;
int height;
public Rect(int width, int height) {
this.width = width;
this.height = height;
}
public boolean equals(Rect p) {
if (width * height == p.width * p.height)
return true;
else
return false;
}
}
public class Test {
public static void main(String arg[]) {
Rect a = new Rect(2, 3);
Rect b = new Rect(3, 2);
Rect c = new Rect(3, 4);
if (a.equals(b))
System.out.println("a is equal to b");
if (a.equals(c))
System.out.println("a is equal to c");
if (b.equals(c))
System.out.println("b is equal to c");
}
}
실행 결과
a is equal to b
'코딩 > JAVA' 카테고리의 다른 글
String 활용 (0) | 2016.06.30 |
---|---|
charAt() 메소드 (0) | 2016.06.30 |
Wrapper 클래스 (0) | 2016.06.30 |
평균값 구해보기 (0) | 2016.06.29 |
static 필드와 메소드 사용 연습 (0) | 2016.06.29 |