There are several compelling reasons for using nested classes, among them:
- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- Nested classes can lead to more readable and maintainable code.
Java Gossip: 內部類別(Inner class)
- 使用內部類別的好處在於可以直接存取外部類別的私用(private)成員,舉個例子來說,在視窗程式中,您可以使用內部類別來實作一個事件傾聽者類別,這個視窗傾聽者類別可以直接存取視窗元件,而不用透過參數傳遞。
- 另一個好處是,當某個Slave類別完全只服務於一個Master類別時,我們可以將之設定為內部類別,如此使用Master類別的人就不用知道 Slave的存在。
So what are inner classes good for anyway?
The advantages of inner classes can be divided into three categories:
- an object-oriented advantage,
- an organizational advantage, and
- a call-back advantage.
沒有留言:
張貼留言