为什么我们被限制在java中的内部类中声明静态成员变量?

 _Yoha 发布于 2023-02-04 20:14

考虑下面的例子为什么在内部类中继承静态变量没有任何限制,我们被限制在内部类中声明静态成员变量?

public class Outer {

    public class Inner {

        public static String notAllowed;
        /* Above line give following compilation error 
         The field notAllowed cannot be declared static in a non-static inner type, unless initialized with a constant expression
         */

    }

}

但是现在如果我的内部类扩展了包含静态变量的其他类,那么这样可以正常工作.考虑以下代码:

public class Outer {

    public class Inner extends InnerBase {
        /* Since it extends InnerBase so we can access Outer.Inner.allowed */ 
        public Inner(){
             Outer.Inner.allowed = null; // Valid statement
        }
    }

}

public class InnerBase {

    public static String allowed;

}

那么在内部类中限制静态变量的原因是什么,因为它可以通过继承来实现?我错过了非常基本的东西吗?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有