[JAVA] On Inner Class: A Dilemma

One of the purposes of introducing inner classes in Java is to protect them from being accessed from outside their surrounding classes. Problem is while we choose to encapsulate a specific functionality into a class, why do we limit its visibility at the same time?

1. To factor it out from the surrounding class in order to organize our code in a more structural way;

2. To preserve the ability to freely modify the inner class in the future; present reusability sometimes conflicts with future flexibility. To elaborate on this issue, consider one situation where we define part of a larger class(ClassA) as another class--------instead of one of its inner class--------and for further reference we call this class ClassB. And apart from ClassA yet another class(ClassC) also composes ClassB, as illustrated by the following diagram:


A Diagram Illustrating the Relationship Between Class A B & C

Reusability has been achieved--------ClassB is being reused by ClassA & ClassC.

Now suppose ClassA need to be revised to meet some new requirements and this can't be done without also touching ClassB. Since ClassC has composed ClassB, it can't avoid being affected. This is how present reusability sometimes conflicts with future flexibility.

In contrast, when implementing ClassA & ClassC, if we'd chosen to define ClassB as inner classes of their own in the first place, ClassA & ClassC would have had been able to evolve independently without affecting one another:


ClassB as Inner Classes of Class A & C
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 上了车,找一个靠窗的位置坐下 夕阳撒在脸庞是太阳的余晖 车子慢悠悠地行走 不管多美的风景和人儿们 在投射到眼球片刻...
    叫我梅芳就好阅读 485评论 1 1
  • 这里所说的干货,就是部分jianshuer疯狂收集点赞的那种。那么,干货的反义是什么?湿货?水货?骚货?都似有贬义...
    平原猫阅读 1,147评论 2 2