티스토리 뷰

IT/JAVA

[JAVA] 예제:EQUALS() 만들기

긍정탁 2017. 7. 14. 11:06

Circle 클래스

- int 타입의 radius의 필드를 가지는 Circle 클래스를 작성하고, 두 Circle 객체의 반지름이 같으면 두 객체가 같은 것으로 판별 하도록 equals() 작성

- 생성자는 필드 초기화

 

Rect 클래스

- int 타입의 width, height 의 필드를 가지는 Rect 클래스를 작성하고, 두 Rect 객체의 width, heght 필드에 의해 구성되는 면적이 같으면 두 객체가

같은 것으로 판별하도록 equals()를 작성하라.

- Rect 생성자에서는 widht, height 필드를 인자로 받아 초기화

 

 

소스코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package today;
 
class Rect{
    int width , height;
    Rect(int width,int height)
    {
        this.width = width;
        this.height = height;
    }
    public boolean equals(Rect r)
    {
        if((width*height)==(r.width*r.height))
            return true;
        else
            return false;
    }
}
 
class Circle{
    int radius;
    Circle(int radius)
    {
        this.radius = radius;
    }
    public boolean equals(Circle c){
        if(radius==c.radius)
            return true;
        else
            return false;
    }
}
 
public class todays170714 {
 
 
    public static void main(String args[]){
        Circle a = new Circle(4);
        Circle b = new Circle(4);
        Rect c = new Rect(3,4);
        Rect d = new Rect(2,6);
 
        if(a==b)
            System.out.println("a==b");
        if(a.equals(b))
        {
            System.out.println("a is equal to b");
        }
        if(c.equals(d))
        {
            System.out.println("c is equal to d");
        }
    }
}
 
cs

 

해설

첫번째 조건문은 주소비교이기때문에 엄연히 Circle a 와 Circle b만을 두고 보면 당연히 결과는 false 이다.

하지만,

equals 함수에서는 두 반지름을 비교하는거기 때문에 반지름이 같으므로 true를 넘겨주어 if블록 안을 실행하게 된다.

세번째 조건문에서는 입력받은 두개의 인자가 서로 다를지라도 , equals 함수에서 두인자의 곱을 비교하였기때문에 true를 넘겨주어 if 블록 안을 실행하게 되는것이다.

출력화면

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31