java内部类多继承_使用内部类让Java实现“多继承”

使用内部类让Java实现“多继承”

众所周知,Java没有像c++那样支持多继承,但是我们可以使用接口或内部类来模拟实现多继承。

我们使用内部类来实现一个继承自消费者,又继承自生产者的派生类。

实际上Java之所以设计出内部类这个概念,一方面是为了更好的封装性,另一方面就是借助内部类模拟实现多继承。

首先我们定义一个消费者抽象基类

/**

* Consumer Class

*@author androidyue

*Last Modified:2011-12-13 上午11:04:56

*/

public abstract class Consumer {

protected float buyPrice;

protected abstract void buyGoods();

}

以下是生产者抽象基类

/**

* Producer Class

*@author androidyue

*Last Modified:2011-12-13 上午11:04:02

*/

public abstract class Producer {

protected float cost;

protected abstract void produce();

}

使用内部类实现“多继承”的派生子类

/**

*Java实现“多继承”

*@author androidyue

*Last Modified:2011-12-13 上午11:00:25

*/

public class InnerClassDemo extends Producer {

private ConsumerBuyer buyer;

public void desribeMySelf(){

System.out.println("使用Java模拟多继承");

this.produce();

this.buyer=new ConsumerBuyer();

this.buyer.buyGoods();

}

@Override

protected void produce() {

this.cost=100f;

System.out.println("我是生产者,我以每件"+this.cost+"RMB的成本生产一件产品,然后以20000元价格对外出售");

}

class ConsumerBuyer extends Consumer{

@Override

protected void buyGoods() {

this.buyPrice=0f;

System.out.println("我是消费者,我以"+this.buyPrice+"RMB 买了一件售价20000元的商品,不信吧,因为我也是生产者!^_^");

}

}

}

在程序入口调用

/**

* the entrance of application

*@author androidyue

*Last Modified:2011-12-13 上午11:20:06

*/

public class AppMain {

public static void main(String[] args){

InnerClassDemo demo=new InnerClassDemo();

demo.desribeMySelf();

}

} 显示结果: 使用Java模拟多继承 我是生产者,我以每件100.0RMB的成本生产一件产品,然后以20000元价格对外出售 我是消费者,我以0.0RMB 买了一件售价20000元的商品,不信吧,因为我也是生产者!^_^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值