为什么静态字段(不是final)在java中的内部类中受到限制 [英] Why static fields (not final) is restricted in inner class in java

查看:202
本文介绍了为什么静态字段(不是final)在java中的内部类中受到限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么Java禁止内部类中的静态字段?

我正在查看规范并得到内部类中的静态成员不可能是最终编译时间常量。

I was going through the specification and got that it is not possible to have the static member in the inner class which is not final compile time constant .

class HasStatic {
    static int j = 100;
}
class myInnerClassTest {
    class Inner extends HasStatic {
        static final int x = 3;  // OK: compile-time constant
        static int y = 4;  // Compile-time error: an inner class
    }
    static class NestedButNotInner{
        static int z = 5;    // OK: not an inner class
    }
    interface NeverInner {}   // Interfaces are never inner
}

我得到的是为什么我们可以拥有静态最终成员但不能在内部类中使用静态方法?它可以从其所有者类继承静态成员。但为什么不应该呢? OOP的主要伤害是什么?

Whereas I got from the Why can we have static final members but cant have static method in an inner class? that it can inherit the static member from its owner class. But why it shouldn't? What OOP's principal it hurts?

推荐答案

你的班级 myInnerClassTest 不是声明为静态。那么具有静态字段究竟意味着什么?

Your class myInnerClassTest isn't declared as static. So what would that exactly mean for it to have a static field ?

它是


  • 对于所有实例都是一样的,无论封闭实例是什么?

  • 对于具有相同封闭实例的内部类的所有实例都是一样的吗?

乍一看,大多数程序员可能认为这是第一种情况,而(非静态)内部类的封装逻辑应该可能导致第二种选择。无论哪种情况(或两者都有不同的修饰符)都需要新的 static 定义,这可能不是必要的。在任何一种情况下,程序员都会对确切含义感到困惑。

At first sight most programmers would probably think it's the first case, while the encapsulation logic of the (non static) inner class should probably lead to the second choice. Either case (or both with different modifiers) would need a new definition of static which probably wasn't seen as necessary. And in either case programmers would be confused about the exact meaning.

来自规范


内部类是一个非显式或隐式的嵌套类
声明为static。

An inner class is a nested class that is not explicitly or implicitly declared static.

内部类包括local(§14.3),anonymous(§15.9.5)和
非静态成员类(第8.5节)。

Inner classes include local (§14.3), anonymous (§15.9.5) and non-static member classes (§8.5).

内部类可能不会声明静态初始化器(第8.7节)或成员
接口,或者编译 - 时间错误发生。

Inner classes may not declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

内部类可能不会声明静态成员,除非它们是常量
变量(§4.12.4),否则会发生编译时错误。

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.

这篇关于为什么静态字段(不是final)在java中的内部类中受到限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆