Java学习10:继承VS组合

之前我们说过继承可以通过组合来实现,这里我们来探讨两者的区别和用法。

1.概述

继承的主要作用:

  • 代码的复用;
  • 方便建模(is a)

组合的主要作用:

  • 代码的复用;
  • 方便建模(has a)

如果仅仅从复用的角度思考,组合完全可以代替继承。并且组合比继承更灵活。

2.代码分析

下面我们把如下继承代码通过组合实现:
继承代码:鸟类继承父类

public class Animal {
    String name;

    public Animal() {
        super(); // 调用父类Object构造器
    }

    void eat() {
        System.out.println("have a good dinner");
    }
}

class Birds extends Animal {

    public Birds() {
        super();
    }

    @Override
    void eat() {
        super.eat(); // 调用父类的方法
        System.out.println("-------------------"); // 分隔线
        System.out.println("jiujiujiu");
    }

    void fly() {
        System.out.println("Yeah,I can fly~~");
    }
}

调用代码Test类

class Test {
    public static void main(String[] args) {
        Birds b = new Birds();
        b.eat();
    }
}

通过组合实现同样功能:

/**
 * 测试组合
 * 
 * @author Arvin
 *
 */
public class Animal {
    String name;

    public Animal() {
        super();
    }

    void eat() {
        System.out.println("have a good dinner");
    }
}

class Birds {
    Animal animal = new Animal(); // 通过Animal对象完成组合

    public Birds() {
        super();
    }

    void eat() {
        animal.eat(); // 调用Animal类的方法
        System.out.println("-------------------"); // 分隔线
        System.out.println("jiujiujiu");
    }

    void fly() {
        System.out.println("Yeah,I can fly~~");
    }
}

调用代码Test类:

public class Test {

    public static void main(String[] args) {
        Birds b = new Birds();
        b.eat();
        b.animal.eat(); // 也可以通过该方式调用Animal的eat方法
    }
}

可见,通过组合同样可以实现继承的功能,而且,组合可以使用多个类的对象,类似于多继承,因而更加灵活。
但是,从理解的角度来看,
继承是“is a”的概念,即:鸟是动物,因而使用继承更加合理。
组合是“has a”的概念,即:鸟有羽毛,则使用组合更加合理,而使用继承就会变成羽毛继承鸟,不合理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值