๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Programming/Java

16 Composition relationship

by Dowon Kang 2024. 1. 20.

ํ”„๋กœ๊ทธ๋ž˜๋ฐ์—์„œ์˜ "Composite relationship"์™€ "์ƒ์†(Inheritance)"์€ ๊ฐ์ฒด ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ(OOP)์—์„œ ๊ฐ์ฒด ๊ฐ„์˜ ๊ด€๊ณ„๋ฅผ ์„ค๋ช…ํ•˜๋Š” ๋‘ ๊ฐ€์ง€ ๋‹ค๋ฅธ ๊ฐœ๋…์ž…๋‹ˆ๋‹ค. 

Composite relationship์€ ์ผ๋ฐ˜์ ์œผ๋กœ ๊ฐ์ฒด๋“ค ๊ฐ„์˜ "has-a" ๊ด€๊ณ„๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐ ์‚ฌ์šฉ๋˜๋ฉฐ, ์ด๋Š” ํ•œ ๊ฐ์ฒด๊ฐ€ ๋‹ค๋ฅธ ๊ฐ์ฒด๋ฅผ ํฌํ•จํ•˜๊ฑฐ๋‚˜ ๊ทธ ์ผ๋ถ€๋กœ์„œ ์กด์žฌํ•จ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. ๋ฐ˜๋ฉด์— ์ƒ์†์€ "is-a" ๊ด€๊ณ„๋ฅผ ๋‚˜ํƒ€๋‚ด๋ฉฐ, ๊ฐ์ฒด ๊ฐ„์˜ ์ผ๋ฐ˜ํ™”์™€ ํŠน์ˆ˜ํ™”๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

A๋Š” B๋‹ค (A is B) → Inheritance (10%)
A๋Š” B๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค (A has B) → Composition (90%)

 

๋”๋ณด๊ธฐ

// ๋ถ€๋ถ„ ๊ฐ์ฒด
class Engine {
    void start() {
        System.out.println("Engine starting");
    }
}

// ์ „์ฒด ๊ฐ์ฒด
class Car {
    private Engine engine;

    Car() {
        // Composite relationship: Car has-a Engine
        this.engine = new Engine();
    }

    void start() {
        System.out.println("Car starting");
        engine.start(); // Car๋Š” Engine์„ ํฌํ•จํ•˜๊ณ  ์žˆ์Œ
    }
}

 

์—ฌ๊ธฐ์„œ Car ํด๋ž˜์Šค๋Š” Engine ํด๋ž˜์Šค๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. Car๋Š” Engine์„ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฏ€๋กœ Composite relationship์ด ์„ฑ๋ฆฝํ•ฉ๋‹ˆ๋‹ค.

 

 

์ƒ์†๊ณผ Composite relationship์€ ๊ฐ๊ฐ ๋‹ค๋ฅธ ๋ชฉ์ ์„ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฉฐ, ์–ด๋–ค ์ƒํ™ฉ์—์„œ ์–ด๋–ค ๊ฒƒ์„ ์‚ฌ์šฉํ• ์ง€๋Š” ์„ค๊ณ„์˜ ์˜๋„์™€ ํŠน์ •ํ•œ ์š”๊ตฌ์‚ฌํ•ญ์— ๋”ฐ๋ผ ๊ฒฐ์ •๋ฉ๋‹ˆ๋‹ค. ์ƒ์†์€ ์ฝ”๋“œ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜๊ณ  ํด๋ž˜์Šค ๊ฐ„์— ์ผ๋ฐ˜ํ™”์™€ ํŠน์ˆ˜ํ™”๋ฅผ ํ†ตํ•ด ๊ณ„์ธต์„ ํ˜•์„ฑํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋˜๊ณ , Composite relationship์€ ํ•œ ํด๋ž˜์Šค๊ฐ€ ๋‹ค๋ฅธ ํด๋ž˜์Šค๋ฅผ ํฌํ•จํ•˜์—ฌ ๋ณตํ•ฉ์ ์ธ ๊ฐ์ฒด๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

 

 

 


composite relationship refers to a connection between two objects or entities where one is considered a part or component of the other. It implies a "whole-part" association, often involving shared lifecycles between the objects.

Inheritance (IS-A) : IS-A relationship signifies that one object is a type of another. It is implemented using ‘extends’ and ‘implements’ keywords.

Composition : HAS-A relationship signifies that a class has a relationship with another class. For instance, Class A holds Class B’s reference and can access all properties of class B.

 

'Programming > Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

18 Polymorphism  (0) 2024.01.20
17 Abstraction  (0) 2024.01.20
15 Inheritance  (0) 2024.01.20
14 Encapsulation (feat. Access modifier)  (0) 2024.01.20
13 Method  (0) 2024.01.20

๋Œ“๊ธ€