(1)。当我将方法声明为静态,然后使用内部类时对象我遇到以下错误。
不能从静态上下文中引用非静态变量。
(2)。但是当我使用方法声明为实例时,程序就会运行成功。
class Test {
public static void main(String[] args) {
A.show();
}
}
class A {
static void show() {
B ref = new B();
System.out.println(ref.x);
}
class B {
int x = 10;
}
}
(3)。但是当我再次将方法声明为静态并定义此对象时然后程序运行没有任何问题。
static void show() {
B ref = new A().new B();
System.out.println(ref.x);
}
为什么我在上述第一个提示中出现错误,而不是在第三点中。
您不能执行以下操作:
class A {
static void show() {
B ref = new B(); // <- problem is here
System.out.println(ref.x);
}
class B {
int x = 10;
}
}
为了创建B
的实例,您需要在A
方法的类instance
内进行操作,或创建封闭类(class A)
的实例并使用它。
您的其他方法
static void show() {
B ref = new A().new B();
System.out.println(ref.x);
}
就是这样。新的A()
创建一个A
的实例,该实例又创建一个B
的实例。如果要执行以下B ref = new B()
,则需要将B
类声明为static
。但是,那么您可能还有其他问题需要解决。
查看讨论此问题的Java Tutorials。
让我们考虑以下示例:
public class Laptop {
public static void main(String[] args) {
Laptop.doThis(); //this will throw error
new Laptop().doThis(); // this will not throw error
InnerClass innerClass = new InnerClass(); //same as above you cannot call a non-static class from a static method
System.out.println(innerClass.x);
}
void doThis()
{
System.out.println("Something");
}
class InnerClass
{
int x=10;
}
}
doThis()方法本质上是非静态的,无法从静态方法访问,并且与类相同。
您可以参考以下资源: