클래스간의 관계결정 - 상속 vs 포함

이정민·2021년 10월 16일
0

상속 Vs 포함

가능한 한 많은 관계를 맺어주어 재사용성을 높이고 관리하기 쉽게 한다.
is-a와 has-a 를 가지고 문장을 만들어 본다.

원(Circle)은 점(Point)이다. - Circle is a Point.
원(Circle)은 점(Point)을 가지고 있다. - Circle has a Point.   O

상속관계 == '~은 ~이다. (is-a)'
포함관계 == '~은 ~을 가지고 있다. (has-a)'

class Point {
   int x;
   int y;
}
---------------------------
// 상속
class Circle extends Point{
   int r; // 반지름(radius)
}

// 포함
class Circle {
   Point c = new Point(); // 원점
   int r; // 반지름(radius)
}

// Circle은 Point를 가지고 있기 때문에 포함이 더 알맞다.

대부분의 관계은 포함관계이고,
기존의 클래스에 새로운 기능이 추가된 새로운 클래스를 만들 때 상속관계



예제를 이클립스로 직접 연습

class Shape {
	String color = "blue";
	void draw() {
		
	}
}

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

	public static void main(String[] args) {
		
		class Circle extends Shape {
			Point center;
			int r;
			
			Circle() {
				this(new Point(0,0),100);
			}
			Circle(Point center, int r) {
				this.center = center;
				this.r = r;
			}
		}
		class Triangle extends Shape {
			Point[] p;
			
			Triangle(Point[] p) {
				this.p = p;
			}
		}
		Circle c1 = new Circle();
		Circle c2 = new Circle(new Point(150,150),50);
		System.out.println(c1.center.x);
		System.out.println(c1.r);
		System.out.println(c2.center.x);
		System.out.println(c2.r);
		
		Point[] po = {new Point(100,100), new Point(140,50), new Point(200, 100)};
		Triangle t1 = new Triangle(po);
		System.out.println(t1.p[1].x);
		System.out.println(t1.p[1].y);
	}

}

// 결과
// 0
// 100
// 150
// 50
// 140
// 50

내가 이해가 가지않았던 부분(잊지말기)

Circle c1 = new Circle();
Circle c2 = new Circle(new Point(150,150),50);

Point[ ] po = {new Point(100,100), new Point(140,50), new Point(200, 100)};
Triangle t1 = new Triangle(po);

당연한 건지도 모르지만 위의 인스턴스를 생성할 때 배열이 들어가니깐 잠깐 동안 혼란이 왔다.
지금은 이해했으니깐 까먹기 전에 정리

(vertex : 꼭짓점)


1) Triangle t1 = new Triangle() 인스턴스를 생산하기 전에

2) Class Triangle의 포함관계인 Point의 인스턴스 생산부터 해야되서

3) Point[ ] vertex = {new Point(100,100), new Point(140,50), new Point(200, 100)}처럼 Point의 인스턴스들을 생산한 후
(vertex가 new Point 인스턴스 주소들을 가지고 있다.)

4) Triangle t1 = new Triangle(vertex) ; 인스턴스를 생성해준다.

5) 생성자 Triangle(Point [ ] p) {
this.p = p;
}의 매개변수 Point [ ] p에 vertex가 전달되어 대입되고 this.p를 통해 Point[ ] p ; 에 주소를 전달한다.

6) Triangle t1은 class Triangle 참조변수인 p를 통해서 값을 뽑아 낼 수 있다. ( System.out.println(t1.p[0].x 배열의 첫번째 x값이, t1.p를 하면 주소 값이 나온다.)

profile
안녕하세요.

0개의 댓글