内部类用处的思考

//: innerclasses/MultiImplementation.java
// With concrete or abstract classes, inner
// classes are the only way to produce the effect
// of "multiple implementation inheritance."
package innerclasses;
class D {
}

abstract class E {
}

class Z extends D {
E makeE() {
return new E() {
};
}
}

public class MultiImplementation {
static void takesD(D d) {
}

static void takesE(E e) {
}

public static void main(String[] args) {
Z z = new Z();
takesD(z);
takesE(z.makeE());
}
}


thinking in java 上说内部类是为了解决多继承问题(the inner class is as the rest of the solution of the multiple-inheritance problem),如上代码。

那么,为什么我们需要多继承?为什么将一个类嵌套在另一个类中来实现另外的类呢?为什么不将内部类移出来作为一个平常的类呢?

最深层次的原因是内部类的特性:内部类可以访问它所在的外部类的所有元素,包括私有成员和私有方法。也就是说实现了某一接口或类的内部类需要访问外部类的元素来实现自身功能,或者说内部类与外部类结合来实现某种功能,我认为这才是内部类的最终用法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值