Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 Re:anonymouse inner class的问题 [Re:daywalker]
film2000



CJSDN高级会员


发贴: 57
积分: 50
于 2003-04-18 18:43 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
anonymous inner class可以访问外部类的类变量,但不能访问外部函数的一般变量,除非该变量为final类型.
public class Test
{
  String classString = "classString";
  
  public void testOne()
  {
    String methodString = "methodString";
    final String methodStringFinal = "methodStringFinal";
    System.out.println(
      new Object()
      {
        public String toString()
        {
          String s = classString;///OK!
          s += methodStringFinal; ///OK!
          s += methodString;//ERROR
          return s;
        }
      }
    Wink;
  }
}

原因如下:当testOne方法退出时,methodString可以被当作垃圾回收掉,因而methodString的生命期结束,但是anonymouse inner class不会因为testOne方法退出而消亡,所以必须把外部临时变量定义为final类型,这样临时变量就不会放在stack,而放在专门的内存里.

我讲的不是很清楚,不知各位能否看懂!》




话题树型展开
人气 标题 作者 字数 发贴时间
6002 anonymouse inner class的问题 daywalker 1999 2003-04-17 17:40
5686 Re:anonymouse inner class的问题 Jove 56 2003-04-17 17:44
5099 Re:anonymouse inner class的问题 jiangns3000 275 2003-04-17 21:55
5147 Re:anonymouse inner class的问题 floater 249 2003-04-18 00:30
5039 Re:anonymouse inner class的问题 jiangns3000 366 2003-04-18 16:59
5583 Re:anonymouse inner class的问题 film2000 663 2003-04-18 18:43
5009 Re:anonymouse inner class的问题 jiangns3000 1192 2003-04-18 20:54
5031 Re:anonymouse inner class的问题 floater 530 2003-04-19 06:04
5033 Re:anonymouse inner class的问题 jiangns3000 17 2003-04-19 12:34

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923