A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 coolzhou9527 于 2015-3-15 22:49 编辑

毕老师说:内部类定义局部变量时,不可以访问他所在的局部中的变量,只能访问被final修饰的局部变量。

但是我写代码时,没有用final修饰,编译依然通过。
代码如下:
  1. /*
  2. 内部类定义在局部时,
  3. 1,不可以被成员修饰符修饰
  4. 2,可以直接访问外部类中的成员,因为还持有外部类中的引用
  5. 但是不可以访问他所在的局部中的变量,只能访问被final修饰的局部变量

  6. */

  7. class Outer
  8. {
  9.         int x = 3;

  10.         void method()
  11.         {
  12.                 int y = 4;//这句我没有用final修饰
  13.                 class Inner
  14.                 {
  15.                         void function()
  16.                         {
  17.                                 System.out.println(y);
  18.                         }
  19.                 }
  20.                 new Inner().function();
  21.         }
  22. }


  23. class  InnerClassDemo3
  24. {
  25.         public static void main(String[] args)
  26.         {
  27.                 Outer out = new Outer();
  28.                 out.method(7);
  29.                 out.method(8);
  30.         }
  31. }
复制代码

但是毕老师的视频里编译没有通过,有大神知道是怎么回事吗?
毕老师视频截图如下:



6 个回复

正序浏览
wwwlcy 中级黑马 2015-3-16 18:31:28
7#
我也想知道,outer类中的void method(),为什么没有调用.

回复 使用道具 举报
局部内部类访问局部变狼,局部变量是要被final修饰,因为,局部方法运行完就会结束,局部变量也会消失,但是内部类被创建后还在椎内存,并不会马上消失,他用到的变量变量确消失,,能不报错吗。而你的程序,写的有错,你根本没有调用到你外部类所定义的方法method();(注意无参的)
回复 使用道具 举报
我也想知道答案
回复 使用道具 举报
你在逗我么宝贝,你调用了method传了int行的值。
而你method方法根本就没接收任何值。你这个78是怎么打印出来的?
回复 使用道具 举报

我再次编译,运行还是没有报错代码如下:

  1. class Outer
  2. {
  3.         int x = 3;

  4.         void method()
  5.         {
  6.                 int y = 4;//这句我没有用final修饰
  7.                 class Inner
  8.                 {
  9.                         void function()
  10.                         {
  11.                                 System.out.println(y);
  12.                         }
  13.                 }
  14.                 new Inner().function();
  15.         }
  16. }


  17. class  InnerClassDemo3
  18. {
  19.         public static void main(String[] args)
  20.         {
  21.                 Outer out = new Outer();
  22.                 out.method(7);
  23.                 out.method(8);
  24.         }
  25. }
复制代码
结果如图:




回复 使用道具 举报
  1. package pack;
  2. class Outer
  3. {
  4.     int x = 3;
  5.         void method(){
  6.         int y = 4;//这句我没有用final修饰
  7.         class Inner{
  8.             void function(){
  9.                 System.out.println(y);
  10.             }
  11.         }
  12.         new Inner().function();
  13.     }
  14. }
  15. class  InnerClassDemo3 {
  16.     public static void main(String[] args) {
  17.         Outer out = new Outer();
  18.         out.method();
  19.         out.method();
  20.     }
  21. }
复制代码


QQ截图20150315224800.png (2.56 KB, 下载次数: 7)

QQ截图20150315224800.png
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马