본문 바로가기
Java

상속 괜찮은가? (컴포지션)

by bloodFinger 2020. 8. 10.

 

부모클래스

class Person{
    void eat(String food){
        System.out.println("먹다");
    }
    void eatAll(String[] foods){
        for (String a: foods) {
            eat(a);
        }
    }
}

 

 

 

상속 받은 자식 클래스

class Grandfather extends Person {
    private int count = 0;

    @Override
    void eat(String food) {
        count++;
        super.eat(food);
    }

    @Override
    void eatAll(String[] foods) {
        count = count  + foods.length;
        super.eatAll(foods);
    }

    public int getCount() {
        return count;
    }
}

 

결과

public class 상속 {
    public static void main(String[] args) {
        Grandfather g = new Grandfather();
        g.eat("헴벅");
        System.out.println(g.getCount());

        Grandfather gg = new Grandfather();
        gg.eatAll(new String[]{"햄벅" , "피자" , "파스타"});
        System.out.println(gg.getCount());
     }
}

1

6

 

 

 

 

컴포지션 클래스

class ModifyGrandfather extends Person{
    private Person person;

    ModifyGrandfather(Person person){
        this.person = person;
    }

    @Override
    void eat(String food) {
        person.eat(food);
    }

    @Override
    void eatAll(String[] foods) {
        person.eatAll(foods);
    }
}

class UltraGrandfather extends ModifyGrandfather{

    private int count = 0;

    UltraGrandfather(Person person) {
        super(person);
    }

    @Override
    void eat(String food) {
        count++;
        super.eat(food);
    }

    @Override
    void eatAll(String[] foods) {
        count = count + foods.length;
        super.eatAll(foods);
    }

    public int getCount() {
        return count;
    }
}

 

결과

public class 상속 {
    public static void main(String[] args) {        
        UltraGrandfather m = new UltraGrandfather(new Person());
        m.eatAll(new String[]{"햄벅" , "파스타" , "맥주"});
        System.out.println(m.getCount());   
    }
}

3

'Java' 카테고리의 다른 글

레거시 코드 변경  (0) 2021.06.13
리펙토링 - 일급컬렉션 사용기  (0) 2021.05.28
제네릭의 모든것  (0) 2020.08.08
객체직렬화 ?  (0) 2020.02.23
Network - TCP 통신  (0) 2020.01.16