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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 马姗姗 中级黑马   /  2014-1-6 13:47  /  1540 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 马姗姗 于 2014-1-6 22:04 编辑

class Outer
{
        int num = 4;
        //内部类。
         class Inner
        {
          static int num = 5;    //为什么会出现这种情况???
                void method()
                {
                int num = 6;
                System.out.println("method run .."+Outer.this.num);
                        System.out.println("method run .."+this.num);
                }
        }
        public void show()
        {
                Inner in = new Inner();
                in.method();
        System.out.println("num="+this.num);
        System.out.println("num="+in.num);
        }
}
        class InnerClassDemo
{
        public static void main(String[] args)
        {
                new Outer().show();
                new Outer().new Inner().method();
        }
}

InnerClassDemo.java:7: 内部类不能有静态声明
          static int num = 5;
                     ^
1 错误

为什么为出错呢?

1 个回复

倒序浏览
你的 num 为 static,为类变量; 而你的局部内部为非静态的成员变量,所以,非静态的不能用静态的成员变量;修改方案:可以把内部类改为 静态的或者把你的 num,改为 final static int num;就可以了。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马