KangMoo
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 상속과 컴포지션 ## 상속 - 상속(Inheritance) : 객체 지향 4가지 특징중 하나로서 클래스 간의 계층적인 관계를 구성하는 방법 - 클래스 상속을 통해 자식 클래스는 부모 클래스의 자원을 물려 받게 되며, 부모 클래스와 다른 부분만 추가하거나 재정의함으로써 기존 코드를 쉽게 확장할 수 있다. - 상속 관계를 is-a 관계라도 표현하기도 한다 ![](https://i.imgur.com/AFlaPpf.png) ```java class Animal { void breathe() { System.out.println("숨을 쉰다."); } } class Dog extends Animal { void bark() { System.out.println("멍멍!"); } } public class InheritanceExample { public static void main(String[] args) { Dog dog = new Dog(); dog.breathe(); // 숨을 쉰다. dog.bark(); // 멍멍! } } ``` **상속은 장점이 많지만 단점 역시 존재한다** - 강한 결합 : 상속은 부모 클래스와 자식 클래스 사이에 강한 결합을 만든다. 이로 인해 부모 클래스의 변경이 자식 클래스에 영향을 미칠 수 있으며, 유지 보수와 확장이 어려워질 수 있다. - 강한 결합이란 두 개 이상의 클래스나 컴포넌트가 서로 긴밀하게 연관되어 있는 것을 의미 - 코드의 재사용성 제한 : 자바에서 다중 상속을 지원하지 않기 때문에 자식 클래스는 단일 부모 클래스로부터만 상속받을 수 있다. 이로 인해 코드의 재사용성이 제한될 수 있다. - 상속 깊이 증가문제 : 클래스 계층 구조가 복잡해질수록 상속 깊이가 깊어지고, 코드의 가독성과 이해도가 떨어진다. 이 경우, 코드를 이해하고 디버깅하는 데 어려움이 발생할 수 있다. - 캡슐화 위반 : 상속은 부모 클래스의 구현 세부사항이 자식 클래스로 노출되기 쉽다. 이로 인해 캡슐화 원칙이 약화되며, 코드의 안정성과 유지 보수성이 저하될 수 있다. - 상속 오용 : 개발자들이 코드의 재사용을 목적으로 상속을 남용할 수 있다. 이로 인해 불필요한 클래스 계층이 생성되고, 코드의 복잡성이 증가한다. 상속을 사용할 때는 신중하게 판단해야 한다. - 상속 사용 시에는 부모 클래스의 내부 구현에 대해 상세하게 알아야 한다 - 유연함 문제 : 상속 관계는 컴파일 타임에 결정되고 고정되기 때문에 코드를 실행하는 도중에 변경할 수 없다. --- ## 컴포지션 - 컴포지션(Composition) : 필드로 클래스의 인스턴스를 참조하게 만드는 설계 방법 - 합성의 방식을 사용 - 각 구성 요소 클래스는 독립적으로 변경되고 테스트될 수 있다. - 클래스 간의 결합도를 낮춰 유연한 설계를 가능하게 한다. - 느슨한 결합 - 상속의 한계를 극복하여 다중 상속과 비슷한 효과를 얻을 수 있다. - 컴포지션 관계를 has-a 관계라도 표현하기도 한다 ```java class Processor { void process() { System.out.println("처리 중..."); } } class Computer { private Processor processor; Computer() { processor = new Processor(); } void startComputer() { processor.process(); System.out.println("컴퓨터 시작"); } } public class CompositionExample { public static void main(String[] args) { Computer computer = new Computer(); computer.startComputer(); // 처리 중... 컴퓨터 시작 } } ``` **컴포지션은 상속의 단점을 보완해주지만 역시 단점을 가지고 있다.** - 중복 코드: 컴포지션을 사용하면 각 구성 요소 클래스의 메소드를 호출하는 코드를 여러 클래스에서 중복해서 작성해야 할 수 있다. 상속을 사용할 경우 이러한 중복 코드를 최소화할 수 있다. - 인터페이스 구현: 구성 요소 클래스의 메소드를 외부로 노출하려면, 상위 클래스에 인터페이스를 구현해야 할 수 있다. 이 경우, 상위 클래스에 구성 요소 클래스의 메소드와 매핑되는 메소드를 정의해야 하며, 이로 인해 코드가 복잡해질 수 있다. - 간접성: 컴포지션은 간접적인 방식으로 클래스 간의 관계를 구현한다. 이로 인해 코드를 이해하고 디버깅하는 데 어려움이 있을 수 있다. - 성능: 컴포지션은 상속에 비해 약간의 성능 저하가 발생할 수 있다. 구성 요소 클래스의 메소드를 호출할 때, 상위 클래스를 통해 간접적으로 호출되기 때문이다. 하지만 대부분의 경우 이러한 성능 차이는 미미하며, 설계의 유연성과 유지 보수성을 향상시키는 데 초점을 맞추는 것이 더 중요하다. --- ## 상속 vs 컴포지션 - 둘 다 재사용성을 위한 방법 - 상속으로 해결할 수 있는 많은 문제를 컴포지션으로도 가능 - 그 반대도 가능 - 순전히 기술적인 관점 - 역사적으로 사람들의 선호는 왔다갔다 한다 - 초창기에는 상속을 과도하게 선호 - 그 후 무조건 컴포지션이 답이라는 잘못된 조언을 많이 따랐음 (현재진행형) - OO에서 가장 큰 결정사항 중 하나 : 상속 vs 컴포지션 중 하나를 고르는 것 - 가이드라인 - 실생활에서 개채들끼리의 관계를 기준으로 선택 - has-a 관계 : 컴포지션 - is-a 관계 : 상속 - 물론 훌륭한 프로그래머들은 필요에 따라 이 규칙을 어긴다. --- ### 상속과 컴포지션 선택 시 고려할 사항 - 기계상의 차이 때문에 하나를 골라야 할 때 (메모리 상의 차이는 용량보다는 실행 성능에 영향을 미친다) - 상속 : 개체 생성 시, **메모리가 하나의 덩어리**다. 개체가 한 번에 캐시 메모리에 들어갈 가능성이 높다. - 컴포지션 : 개체 생성 시 **메모리가 여러 덩어리**다. 개체 내 부품 수 만큼 캐시 메모리로 로딩할 가능성이 높다. - 즉, 좋은 성능이 필요하다면 상속을 고르는 것이 더 좋다. - 용도 때문에 상속을 고를 수밖에 없을 때 - 명령 하나로 여러 형의 개체를 한번에 처리하고 싶을 때 (다형성) - 관리의 효율성을 고려할 때 - 일반적으로 메서드 중복을 피하기 위해서는 상속을 사용하는게 좋다. 하지만 깊은 상속 관계일 경우 (부모 자식간의 단계가 많을 경우) 상위 부모개체 클래스의 코드를 수정할 경우 하위 모든 자식 클래스에서 문제가 발생하지 않는지 확인해야 하는 불편함이 있다. 해당 문제는 컴포지션도 문제가 있긴 하지만 상속보다는 덜하다. - 인터페이스나 다형성이 이러한 문제를 조금 완화시켜준다 - 그 외 일반적인 상황 - has-a 와 is-a 관계에 충실하자 ![](https://i.imgur.com/8JkhOyK.png) > **강한 결합 vs 느슨한 결합** > - 강한 결합(Strong Coupling) > - 장점 > - 간단한 시스템에서는 강한 결합이 구현이 빠르고 쉬울 수 있다. > - 단점 > - 한 클래스의 변경이 다른 클래스에 영향을 미쳐 유지 관리와 확장이 어렵다. > - 코드의 재사용성이 낮아진다. 강한 결합된 클래스는 다른 시스템에서 사용하기 어려울 수 있다. > - 오류 수정 및 기능 추가에 대한 비용이 증가하며, 시스템의 안정성이 낮아질 수 있다. > - 느슨한 결합(Loose Coupling) > - 장점 > - 클래스 간의 연결이 최소화되어 변경에 더 유연하게 대응할 수 있다. > - 코드의 재사용성이 높아진다. 느슨한 결합된 클래스는 다른 시스템에서 사용하기 쉽다. > - 유지 관리와 확장성이 향상된다. 한 클래스의 변경이 다른 클래스에 미치는 영향이 적어진다. > - 시스템의 안정성이 높아진다. 오류 수정 및 기능 추가에 대한 비용이 감소한다. > - 단점 > - 초기 설계 및 구현에 시간이 더 소요될 수 있다. > - 인터페이스, 추상 클래스, 디자인 패턴 등을 사용하여 느슨한 결합을 구현하기 위해서는 더 많은 계획과 구조화가 필요하다.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully