티스토리 뷰

안녕하세요 Shiny Ocean입니다.

 

자바를 주제로한 다섯번째 포스팅은 부모와 자식 클래스의 상속관계를 응용하여 다루어 보겠습니다.

 

 

저의 경우에는 도형을 주제로 삼았습니다. 점이 모여 삼각형을 표현하는 좌표가 되고 삼각형을 상속

받아 색깔이 있는 삼각형을 클래스로 구현하였습니다.

그리고 선언된 컬러삼각형들의 요소를 비교하여 같은지 다른지를 판별하는 메소드를 작성하였습니다.

 

 

Java 예제문제 6 - 삼각형 클래스에 equals만들어보기

<step 1>

점을 표현할수 있는 클래스를 만들기

<step 2>

삼각형의 표현을 점3개의 Point값(x,y) 로 표현하는 TriPoint를 만들었습니다.

<step 3>

step 2의 TriPoint클래스를 상속받아 색이 있는 삼각형을 정의하는 ColorTriangle 클래스를 만들었습니다.

<step 4>

step 3의 ColorTriangle로 선언된 삼각형 객체들을 비교하는 equals메소드를 따로 만들었습니다.

<Final step >

선언된 colorTriangle들의 정보를 한번 출력후 각 삼각형들의 좌표값을 비교후 동일여부를 출력했습니다.

 

+ <option> – colorTriangle을 만들어 색깔이 있는 삼각형과 비교하는 equals 만들어보기

 

 

 

 

해결 과정)

<step 1>

예제에 나와있는 Point class 그대로 이용하기위해 따로 바꾸지 않았습니다.

 

class Point{

        int x,y;

        public Point(int x, int y) {this.x = x; this.y = y;}

        public String toString() {return "point(" + x + "," + y + ")";}

}

 

 

먼저 Point라는 클래스를 분석해보면

X y라는 정수변수를 선언후 생성자를 통해 그값을 초기화 합니다.

(만약 x y 값이 예제 6-1처럼 private으로 선언되어 있다면, getX(){return x}; 이런식으로 값을 반환해주는 메소드를 따로 작성해야합니다.)

 

toString() 메소드는 리턴타입이 String이고 생성자를통해 초기화된 x,y값의 정보를 String으로 리턴해주는 메소드입니다.

toString() 메소드를 <step 3>에서 컬러삼각형의 정보를 리턴하는 toString메소드에서도 불러와 코드를 간소화하겠습니다.

 

<step 2>

삼각형의 표현을 3개의 Point(x,y) 표현하는 TriPoint 만들었습니다.

 

삼각형을 표현하기 위해서 가장 적절한 방법은 삼각형을 세점을 (x,y)좌표로 표현하는것이었습니다.

추후 삼각형 객체를 비교하기위한 메소드를 생성할때도 3점의 좌표가 같을시 동일한 삼각형으로 정의하였습니다.

 

TriPoint 클래스안에는 세점의 좌표를 초기화하기위해 <step 1> point 객체를 3 선언하고

setPoint(int a, int b){…} 통해 각점에 좌표값을 초기화했습니다.

 

EX) Point point1,point2,point3;

위의 예시그림과 예시 코드와 같이 Point1,2,3 좌표를 초기화해주는 클래스 Tripoint 생성해준후

이를 상속받아 삼각형을 구성하는 클래스인 ColorTrianlge 클래스를 <step 3>에서 다뤄 보겠습니다.

 

<step2> Java Code)

class TriPoint{

        Point point1,point2,point3;

       

        public void setPoint1(int a, int b){

                 point1 = new Point(a,b);

        }

        public void setPoint2(int a, int b){

                 point2 = new Point(a,b);

        }

        public void setPoint3(int a, int b){

                 point3 = new Point(a,b);

        }

}

 

<step 3>

<step 2> TriPoint클래스를 상속받아 색이 있는 삼각형을 정의하는 ColorTriangle 클래스를 만들었습니다.

 

제가 정의한 삼각형의 요소들은 <1.이름> , <2.색깔> , <3.세점의 좌표> 입니다.

이름을 제외한 색깔과 좌표를 기준으로 <step4>에서 비교연산(equals) 실행하겠습니다.

 

1.이름은 name이라는 String 선언후, 생성자를 통해 초기화하였습니다.

(이름 name변수는 toString()메소드로 반환후 출력시 객체를 구별하기위해서 만든 것이기 때문에 비교연산의 기준으로는 포함시키지 않았습니다.)

 

2.색깔은 삼각형 객체를 비교할 스트링도 비교연산을 해보고싶어서 추가해보았습니다

 

3.세점의 좌표는 이미 <step2> TriPoint클래스를 통해 선언했기 때문에 그대로 상속받아 사용하겠습니다. – class ColorTriangle extends TriPoint

 

 

+ 삼각형이 선언되었는지 스트링을 통해 검사 할수 있는 toString메소드를 선언했습니다

public String toString() {

                 return name+" is \"" + color + "\" color and Point is\n \"" +point1.toString() + "    " + point2.toString() + "    " + point3.toString()+"\"";

 

Ex)만약 클래스에 name = “RedTriangleA”, Color = “RED” , point1 = (0,0), point2 = (0,3)

        Point3 = (3,0)이라 초기화 되어있다면 toString메소드를 통해 반환되는 결과입니다.

                RedTriangle is “RED” color and point is

“point(0,0) point(0,3) point(3,0)

       

.

 

<step3> Java Code)

class ColorTriangle extends TriPoint{

        String color;

        String name;

        public ColorTriangle(String name,String color) {

                 this.color = color;

                 this.name  = name;

        }

        public String toString() {

                 return name+" is \"" + color + "\" color and Point is\n \"" +point1.toString()

                 + "       " + point2.toString() + "    " + point3.toString()+"\"";

        }

}

 

<step 4>

<step 3> ColorTriangle 선언된 삼각형 객체들을 비교하는 equals메소드를 따로 만들었습니다.

 

처음에 저는 책의 예시에서 equals메소드가 Object.equals메소드와 무엇이 달라서 복잡한 다운캐스팅까지 필요할까 의문이 들었습니다.

 

System.out.println(colorTri1.point1.x.equals(colorTri2.point1.x));

 

처음에는 메인메소드에서 이렇게 객체의 point1 x좌표끼리 비교를 해보려했지만

오브젝트클래스 내에서 주어지는 equals메소드는 이러한 오류메세지가 출력됩니다.

Cannot invoke equals(int) on the primitive type int

primitive type 호출할수 없다 라고합니다.

 

p.348 <잠깐!> - “Object equals(object obj)메소드는 obj 자기자신의 레퍼런스 == 단순비교하게 만들어저있다, 내용에 대해서는 비교하지 않는다

+개념이 조금 정확하지 않아 구글링을 해보았습니다.

자바의 타입두가지는 primitive reference타입이다, primitive 언어에서 사전 정의되어있는 타입으로 char, int, byte 같은 일반값이고  reference Object 상속한 객체형으로 나타난다

<출처 : https://m.blog.naver.com/PostView.nhn?blogId=beabeak&logNo=50143554381&proxyReferer=https:%2F%2Fwww.google.com%2F>

 

 

따라서 오브젝트클래스의equals메소드는 레퍼런스타입 단순 비교연산이어서 primitive type

(int) colorTri1.point1.x 좌표값을 비교할수없다는 결론을 도출했습니다.

 

 

그러므로 primitive type 비교할수 있도록 메소드를 새로 정의했습니다.

 

 

1 메인메소드가 있는 클래스내에서 객체의 선언이 없이도 바로 사용할수 있도록 Static메소드로 만들었습니다.

 

2 p.343- 모든 클래스는 오브젝트 클래스에 강제로 상속된다.

그러므로 어떠한 obj 들어오던 일단 ColorTriangle클래스로 다운캐스팅 시키면 비교 연산이 가능해집니다. Ex)

ColorTriangle a = (ColorTriangle)objA;

                 ColorTriangle b = (ColorTriangle)objB;

 

 

3 삼각형의 Point들의 int값들을 비교하는 조건문과, color 스트링값을 비교하는 조건문을 &&연산자로 묶어 삼각형의 색깔과 좌표값이 같아야 boolean값이 true return되게 코딩했습니다.

 

 

<step4> Java Code)

public static boolean equals(Object objA, Object objB) {

                

                 ColorTriangle a = (ColorTriangle)objA;

                 ColorTriangle b = (ColorTriangle)objB;

                 if( (a.point1.x ==b.point1.x) && (a.point1.y ==b.point1.y) &&

                                 (a.point2.x ==b.point2.x) && (a.point2.y ==b.point2.y) &&

                                 (a.point3.x ==b.point3.x) && (a.point3.y ==b.point3.y) &&

                                 (a.color.equals(b.color))) {

                         return true;

                 }

                 return false;

        }

 

 

<Final step >

선언된 colorTriangle들의 정보를 한번 출력후 삼각형들의 좌표값을 비교후 동일여부를 출력했습니다.

 

삼각형은 이름과 정보가 다르게 4개를 선언하고 비교해보았습니다.

 

<1> colorTri1 = 이름은 RedTriangleA" 색깔은 "RED” 좌표는 (0,0), (3,0), (0,3)

<2> colorTri2 = 이름은 RedTriangleB" 색깔은 "RED” 좌표는 (0,0), (3,0), (0,3)

<3> colorTri3 = 이름은 BlueTriangle" 색깔은 "BLUE” 좌표는 (0,0), (3,0), (0,3)

<4> colorTri4 = 이름은 RedTriangleC" 색깔은 "RED” 좌표는 (0,0), (5,0), (0,5)

 

(이름은 비교기준이 아닙니다, 삼각형 구분을위해 추가한 스트링입니다.)

 

<1> <2> 색깔과 좌표 모든요소가 동일합니다. 따라서 동일한 삼각형

<1> <3> 좌표는 모두 동일하지만 색깔이 다릅니다. 따라서 동일하지 않은 삼각형

<1> <4> 색깔은 동일하지만 좌표값이 다릅니다. 따라서 동일하지 않은 삼각형

 

 

결과는 콘솔이미지캡쳐 부분에 첨부하겠습니다.

 

<step5> Java Code)

 

public static void main(String[] args) {

                                

                 // 삼각형 세점 좌표 선언

                 ColorTriangle colorTri1 = new ColorTriangle("RedTriangleA","RED");

                 colorTri1.setPoint1(0,0);

                 colorTri1.setPoint2(3,0);

                 colorTri1.setPoint3(0,3);

                

                 ColorTriangle colorTri2 = new ColorTriangle("RedTriangleB","RED");

                 colorTri2.setPoint1(0,0);

                 colorTri2.setPoint2(3,0);

                 colorTri2.setPoint3(0,3);

                

                 ColorTriangle colorTri3 = new ColorTriangle("BlueTriangle","BLUE");

                 colorTri3.setPoint1(0,0);

                 colorTri3.setPoint2(3,0);

                 colorTri3.setPoint3(0,3);

                

                 ColorTriangle colorTri4 = new ColorTriangle("RedTriangleC","RED");

                 colorTri4.setPoint1(0,0);

                 colorTri4.setPoint2(5,0);

                 colorTri4.setPoint3(0,5);

                

        System.out.printf("\n==================================================================");       

                

                 System.out.println("\n"+colorTri1.toString()+"\n");

                 System.out.println("\n"+colorTri2.toString()+"\n");

                 System.out.println("\n"+colorTri3.toString()+"\n");

                 System.out.println("\n"+colorTri4.toString()+"\n");

                        

                 System.out.println("-------------------------------------------------------");      

                

                 System.out.println("Is RedTriangleA same as RedTriangleB ? \n"

                                                          +equals(colorTri1,colorTri2));

                

                 System.out.println("Is RedTriangleA same as BlueTriangleB ? \n"

                                                          +equals(colorTri1,colorTri3));

                

                 System.out.println("Is RedTriangleA same as RedTriangleC ? \n"

                                                          +equals(colorTri1,colorTri4));

        }

 

}

 

 

 

 

전체 코드)

package shape;

class Point{

        int x,y;

        public Point(int x, int y) {this.x = x; this.y = y;}

        public String toString() {return "point(" + x + "," + y + ")";}

}

class TriPoint{

        Point point1,point2,point3;

       

        public void setPoint1(int a, int b){

                 point1 = new Point(a,b);

        }

        public void setPoint2(int a, int b){

                 point2 = new Point(a,b);

        }

        public void setPoint3(int a, int b){

                 point3 = new Point(a,b);

        }

}

class ColorTriangle extends TriPoint{

        String color;

        String name;

        public ColorTriangle(String name,String color) {

                 this.color = color;

                 this.name  = name;

        }

        public String toString() {

                 return name+" is \"" + color + "\" color and Point is\n \"" +point1.toString()

                 + "       " + point2.toString() + "    " + point3.toString()+"\"";

        }

}

 

public class TriangleMain {

       

        //스태틱선언으로 인한 객체생성없이 메소드 사용가능

        public static boolean equals(Object objA, Object objB) {

                

                 ColorTriangle a = (ColorTriangle)objA;

                 ColorTriangle b = (ColorTriangle)objB;

                 if( (a.point1.x ==b.point1.x) && (a.point1.y ==b.point1.y) &&

                                 (a.point2.x ==b.point2.x) && (a.point2.y ==b.point2.y) &&

                                 (a.point3.x ==b.point3.x) && (a.point3.y ==b.point3.y) &&

                                 (a.color.equals(b.color))) {

                         return true;

                 }

                 return false;

        }

       

        public static void main(String[] args) {

                                

                 // 삼각형 세점 좌표 선언

                 ColorTriangle colorTri1 = new ColorTriangle("RedTriangleA","RED");

                 colorTri1.setPoint1(0,0);

                 colorTri1.setPoint2(3,0);

                 colorTri1.setPoint3(0,3);

                

                 ColorTriangle colorTri2 = new ColorTriangle("RedTriangleB","RED");

                 colorTri2.setPoint1(0,0);

                 colorTri2.setPoint2(3,0);

                 colorTri2.setPoint3(0,3);

                

                 ColorTriangle colorTri3 = new ColorTriangle("BlueTriangle","BLUE");

                 colorTri3.setPoint1(0,0);

                 colorTri3.setPoint2(3,0);

                 colorTri3.setPoint3(0,3);

                

                 ColorTriangle colorTri4 = new ColorTriangle("RedTriangleC","RED");

                 colorTri4.setPoint1(0,0);

                 colorTri4.setPoint2(5,0);

                 colorTri4.setPoint3(0,5);

                

        System.out.printf("\n==================================================================");       

                

                 System.out.println("\n"+colorTri1.toString()+"\n");

                 System.out.println("\n"+colorTri2.toString()+"\n");

                 System.out.println("\n"+colorTri3.toString()+"\n");

                 System.out.println("\n"+colorTri4.toString()+"\n");

                        

                 System.out.println("-------------------------------------------------------");      

                

                 System.out.println("Is RedTriangleA same as RedTriangleB ? \n"

                                                          +equals(colorTri1,colorTri2));

                

                 System.out.println("Is RedTriangleA same as BlueTriangleB ? \n"

                                                          +equals(colorTri1,colorTri3));

                

                 System.out.println("Is RedTriangleA same as RedTriangleC ? \n"

                                                          +equals(colorTri1,colorTri4));

        }

 

}

 

 

 

 

결과 콘솔)

 

 

'Language > Java' 카테고리의 다른 글

Java - Final Project  (0) 2021.01.28
Java - Swing, Jslider 스윙과 슬라이더  (0) 2021.01.28
Java - 간단한 끝말잇기 텍스트게임 구현  (1) 2021.01.28
Java - Abstract Class, 추상클래스  (0) 2021.01.28
Java - Class & 생성자  (1) 2021.01.28
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
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
글 보관함