为什么不能从静态上下文引用非静态变量-reg [英] Why non-static variable cannot be reference from a static context - reg
问题描述
可能重复:
不能从静态上下文(java)引用非静态变量
public class DemoJava {
public class Hello {
void fun()
{
System.out.println("This is static fun man!!");
}
}
public static void main(String[] args) {
Hello hello = new Hello();
hello.fun();
}
}
在此示例中,由于我正在尝试从静态方法访问非静态类。精细。例如,如果我在另一个文件中有相同的 Hello
类,并且我做同样的事情,则不会给我错误。
In this example it will give me an error since I am trying to access a non-static class from a static method. Fine. For instance, if I have the same Hello
class in another file and I do the same thing it does not give me an error.
即使在这种情况下,我们也尝试从静态方法访问非静态类。但这不会带来任何错误。为什么?
Even in that case we are trying to access non-static class from static method. But that doesn't give any error. Why?
推荐答案
在此示例中,由于我尝试访问非
In this example it will give me an error since I am trying to access a non-static class from a static method.
不,它会给您一个错误,因为您正试图创建一个内部类的实例(隐式引用封闭类的实例),而您没有封闭类的实例。
No, it will give you an error because you're trying to create an instance of an inner class (which implicitly has a reference to an instance of the enclosing class) when you don't have an instance of the enclosing class.
The问题不是对 fun()
的调用-这是构造函数调用。
The problem isn't the call to fun()
- it's the constructor call.
例如,您可以使用以下方法解决此问题:
For example, you can fix this by using:
DemoJava demo = new DemoJava();
Hello hello = demo.new Hello();
或者您可以通过更改类声明使其成为嵌套而不是内部类到:
Or you could just make it a nested but not inner class, by changing the class declaration to:
public static class Hello
阅读以下内容的第8.1.3节JLS 获取有关内部类的更多信息,以及第15.9.2节,用于确定类实例创建表达式的封闭实例:
Read section 8.1.3 of the JLS for more information on inner classes, and section 15.9.2 for determining enclosing instances for a class instance creation expression:
否则,C是内部对象成员类(第8.5节),然后:
Otherwise, C is an inner member class (§8.5), and then:
-
如果类实例创建表达式是不合格的类实例创建表达式,则:
If the class instance creation expression is an unqualified class instance creation expression, then:
- 如果类实例创建表达式在静态上下文中发生,则将发生编译时错误。
这篇关于为什么不能从静态上下文引用非静态变量-reg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!