[英]Why am I not able to access static inner class through an instance
Let's say we have a class Test
like this, 假设我们有这样的类
Test
,
public class Test {
public static void main(String... args) {
}
public static class InnerTest {
public void test() {
}
}
}
I agree that, I should access static fields using the class name, like 我同意,我应该使用类名访问静态字段,比如
Test.main();
Test.InnerTest obj = new Test.InnerTest();
But we can also access the static member's through instances, 但我们也可以通过实例访问静态成员,
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
I just want to learn why something like this is not possible? 我只是想知道为什么这样的事情不可能? I am not able to completely understand from the errors reported.
我无法从报告的错误中完全理解。
My guess: inner classes were added later, with 1.1. 我的猜测:内部课程后来添加了1.1。 By the time inner classes were being designed it was apparent allowing access to static members through the instance was a mistake.
当内部类被设计时,很明显允许通过实例访问静态成员是一个错误。 It was too late to change this for existing cases but they could avoid adding it for the new functionality.
为现有案例更改此内容为时已晚,但他们可以避免将其添加到新功能中。
Test.InnerTest itest = test.new InnerTest(); Test.InnerTest itest = test.new InnerTest(); - object test does not have method new
- 对象测试没有新方法
Test.InnerTest itest = new test.InnerTest(); Test.InnerTest itest = new test.InnerTest(); - everything on the right side of new operator must by a Type
- 新操作员右侧的所有内容必须由Type输入
Test.InnerTest itest = test.new Test.InnerTest(); Test.InnerTest itest = test.new Test.InnerTest(); - combination of both remarks
- 两个言论的组合
What are really trying to do? 真的想做什么? Create instances of inner classes?
创建内部类的实例? Are you looking for a factory method?
您在寻找工厂方法吗?
IMHO The problem is you are trying to think about it as a "calling method" way and it's nothing related with this since creating a new instance with "new" keyword is a completely different process. 恕我直言问题是你试图将它视为一种“调用方法”的方式,它与此无关,因为用“new”关键字创建一个新实例是一个完全不同的过程。
The syntax for the "new" keyword is defined in the Java Languaje Specification and requires a type name following it. “new”关键字的语法在Java Languaje规范中定义,并且后面需要一个类型名称。 In the case of the static inner classes this identifier has to be constructed relative to the parent class name.
在静态内部类的情况下,该标识符必须相对于父类名构造。
https://docs.oracle.com/javase/specs/jls/se7/jls7.pdf https://docs.oracle.com/javase/specs/jls/se7/jls7.pdf
It is just Java Languaje is build to work this way. 它只是Java Languaje以这种方式构建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.