Language/Java

[Java]클래스간의 관계 결정하기

Hoplin 2022. 1. 7. 14:37
반응형

상속?? 포함관계??

클래스를 작성하는데에 있어서 상속관계를 맺어줄 것인지, 포함관계를 맺어줄것인지를 고민해야한다. 

 

//상속
package Interface2;

class point{
    private int x;
    private int y;
}

class Circle extends point{
    
}

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

    }
}
//포함관계
package Interface2;

class point{
    private int x;
    private int y;
}

class Circle{
    point p = new point();

}

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

    }
}

그럼 언제 상속, 언제 포함관계를 해야할까? 결론적으로 자바는 다중상속을 허용하지 않고, 단일 상속만 가능하다. 그렇기 때문에 비중이 높은 클래스를 상속을 하고 비중이 상대적으로 낮은 클래스에 대해서 포함관계선언을 한다. 이걸 판별하는 방법은 is ~ a / has ~ a 를 가지고 판별을 해보면 된다. is ~a 가 성립되면, 상속관계를, has ~a관계가 성립하면 포함관계를 맺어주면된다.

  • 원은 점이다 : Circle is a Point
  • 원은 점을 가지고 있다 : Circle has a Point

결론적으로 위 예시에서는 두번째 문장이 더 알맞은 것이므로, 판단이 되었기 때문에, 여기서는 포함관계를 사용해 주면된다. 그렇다면 상속이 가능하게 끔 명제를 해보면, '원은 도형이다' 라는 문장에 대해서는 원과 도형은 상속관계를 가지게 된다. 아래 예시코드와 같이 작성할 수 있다.

package Interface2;
import java.util.Arrays;

class Shape{
    private final String color;
    Shape(String color){
        this.color = color;
    }
    Shape(){
        this("Black");
    }
    void draw(){
        System.out.println(this.color + "색 도형을 그리는 중입니다.");
    }
    String getColor(){
        return this.color;
    }
}

class Point{
    int x;
    int y;
    Point(int x, int y){
        this.x = x;
        this.y = y;
    }
    Point(){
        this(10,10);
    }
    String getXY(){
        return "X : " + this.x + " Y : " + this.y;
    }
    @Override
    public String toString(){
        return "(x : " + this.x + " y : " + this.y + ")";
    }
}

// 원은 도형이다 라는 명제가 성립(is ~ a),즉 상속관계를 가진다.
class Circle extends Shape{
    int rad = 30;
    //원은 점을 가지고 있다 라는 명제가 성립(has ~ a), 즉 포함관계를 가진다
    Point p;
    Circle(){
        super("Yellow");
        this.p = new Point(30,30);
    }
    Circle(Point p, String Color){
        super(Color);
        this.p = p;
    }
    // Shape클래스의 메소드 오버라이드
    @Override
    void draw(){
        System.out.println("Center : " + p.getXY() + " Radius : " + this.rad + " Color : " + this.getColor());
    }
    @Override
    public String toString(){
        return "Circle";
    }
}

// 세모는 도형이다라는 명제 성립, 상속관계
class Triangle extends Shape{
    // 세모는 점을 가진다 라는 명제 성립, 포함관계 성립
    Point p[] = new Point[3];

    Triangle(Point[] p){
        this.p = p;
    }

    @Override
    void draw(){
        System.out.printf("Points : " + Arrays.toString(p));
    }
}


class drawtest{
    public static void main(String[] args){
        Point p[] = {
                new Point(10,20),
                new Point(30,40),
                new Point(50,60)
        };
        Triangle t = new Triangle(p);
        Circle c = new Circle(new Point(40,40), "Red");

        c.draw();
        t.draw();
    }
}
반응형