免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4617 | 回复: 5
打印 上一主题 下一主题

什么时候用内嵌类? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-03-29 15:18 |只看该作者 |倒序浏览
有什么优越性呢?

论坛徽章:
0
2 [报告]
发表于 2003-03-29 22:44 |只看该作者

什么时候用内嵌类?

如果内部类只和包含它的外层类有关系, 则可以选择内部类, 也许这样更复合开闭原则。

论坛徽章:
0
3 [报告]
发表于 2003-03-30 11:15 |只看该作者

什么时候用内嵌类?

说的对。
界面上一个按钮的 ActionListener 类只会在这个界面类里才会用到
所以把 ActionListener 类作为界面类的一个 inner class
我基本只是在设计界面时才会用到 inner class

看看这里:

http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
You use nested classes to reflect and enforce the relationship between two classes. You should define a class within another class when the nested class makes sense only in the context of its enclosing class or when it relies on the enclosing class for its function. For example, a text cursor makes sense only in the context of a particular text component.

http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html
Inner classes are used primarily to implement adapter classes like the one shown in this example. If you plan on handling events from the AWT, then you'll want to know about using adapter classes because the event-handling mechanism in the AWT makes extensive use of them.

论坛徽章:
0
4 [报告]
发表于 2003-03-30 13:03 |只看该作者

什么时候用内嵌类?

a text cursor makes sense only in the context of a particular text component.


这句话我不是特别明白
能不能举个例子给说明一下!
:)

论坛徽章:
0
5 [报告]
发表于 2003-03-31 17:34 |只看该作者

什么时候用内嵌类?

呵呵,我也不是太明白,大概就是 text cursor 只知道某个特定的 text component
所以可以作为 text component 的 inner class



举个例子:
比如:我写了一个 ConnectionPool 类来处理和数据库的连接
我想每秒钟检查一下 ConnectionPool 中的 connection 是否 idle,
如果 idle ,就把它回收到 connectionPool 里

做这个工作的类叫做 ConnectionReaper,是一个线程
每秒运行一次,调用 ConnecitonPool 的 reapConnection() 方法

他只需知道 ConnectionPool ,其他都不需要知道
所以可以把 ConnectionReaper 作为 ConnectionPool 的一个 inner class


  1. public class ConnectionPool{
  2.   // the connection array
  3.   Connection[] connections;

  4.   public ConnectionPool(){
  5.     // init the connections
  6.   }

  7.   public Connection getConnection(){
  8.     // return an idle connection
  9.   }

  10.   public void reapConnection(){
  11.     // check each connection, if idle, return this connection to pool
  12.   }

  13.   class ConnectionReaper extends Thread{
  14.     ConnectionPool pool;
  15.     public ConnectionReaper(ConnectionPool pool){
  16.       this.pool = pool;
  17.       start();
  18.     }
  19.     public void run(){
  20.       while(true){
  21.         sleep(1000);
  22.         pool.reapConnection();
  23.       }
  24.     }
  25.   }

  26. }

复制代码

论坛徽章:
0
6 [报告]
发表于 2003-04-01 12:58 |只看该作者

什么时候用内嵌类?

呵呵

cinc
很清楚了!谢谢!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP