假设我们有一个这样的Test类,

public class Test {

    public static void main(String... args) {
    }

    public static class InnerTest {
        public void test() {
        }
    }
}

我同意,我应该使用类名称访问静态字段,例如
Test.main();
Test.InnerTest obj = new Test.InnerTest();

但是我们也可以通过实例访问静态成员的,
Test test = new Test();

test.main(); // Compiler warning but WORKS fine.

// But I can't do any of this.
Test.InnerTest itest = test.new InnerTest(); // Illegal enclosing instance specification for type Test.InnerTest
Test.InnerTest itest = new test.InnerTest(); // test cannot be resolved to a type
Test.InnerTest itest = test.new Test.InnerTest(); // Cannot allocate the member type Test.InnerTest using its compound name when qualified by an enclosing instance. The member type name is resolved relatively to the qualifying instance type

我只想了解为什么这样的事情是不可能的?从报告的错误中我无法完全理解。

最佳答案

我的猜测:内部类后来添加了1.1。在设计内部类时,显然允许通过实例访问静态成员是一个错误。现在为现有情况更改此方法为时已晚,但他们可以避免为新功能添加它。

09-13 04:13