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

Python015

使用内部类让Java实现“多继承”,第1张

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

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

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

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

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

view plainprint?

/** * Consumer Class *@author androidyue *Last Modified     上午 */ public abstract  class Consumer { protected float buyPrice protected abstract void  buyGoods() }

以下是生产者抽象基类

view plainprint?

/** * Producer Class *@author androidyue *Last Modified     上午 */ public abstract class Producer { protected  float cost protected abstract void produce() }

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

view plainprint?

/** *Java实现 多继承

*@author androidyue *Last Modified     上午 */ 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() { st= f System out println( 我是生产者 我以每件 +st+ RMB的成本生产一件产品 然后以 元价格对外出售 ) }

class ConsumerBuyer extends Consumer{

@Override protected void buyGoods() { this buyPrice= f System out println( 我是消费者 我以 +this buyPrice+ RMB 买了一件售价 元的商品 不信吧 因为我也是生产者!^_^ )

}

}

}

在程序入口调用

view plainprint?

/** *  the entrance of application *@author androidyue *Last Modified     上午 */ public class AppMain { public static void main(String[] args){ InnerClassDemo demo=new InnerClassDemo() demo desribeMySelf() }

lishixinzhi/Article/program/Java/hx/201311/25912

java中没有多继承(就是不能继承多个父类),只有多重继承。。比如:\x0d\x0aclass A{\x0d\x0a}\x0d\x0a\x0d\x0aclass B extends A{\x0d\x0a}\x0d\x0a\x0d\x0aclass C extends B {\x0d\x0a}\x0d\x0a可以实现多个接口,比如:\x0d\x0ainterface A{\x0d\x0a}\x0d\x0a\x0d\x0ainterface B{\x0d\x0a\x0d\x0a}\x0d\x0a\x0d\x0aclass C implements A, B\x0d\x0a{\x0d\x0a}