13. 是否可以在static环境中访问非static变量
13. 是否可以在static环境中访问非static变量
不可以,static环境是静态的,在类加载之前就有产生了。而非static变量是在运行时动态产生的,在static环境里调用时,找不到该变量。
- static:属于类本身, 在类加载时初始化, 存储在JVM的方法区里,它们的生命周期与类相同
- 非static:属于类的实例(对象), 只有在new创建对象时才会初始化,存储在堆内存中。
可以通过对象实例来访问非static变量
public class Example {private int nonStaticVariable = 10;public static void main(String[] args) {Example obj = new Example(); // 创建对象实例System.out.println(obj.nonStaticVariable); // 通过对象访问}
}