我在理解非静态变量的处理方式时遇到了问题。我选择使用数组,以便轻松检索其内存地址。
考虑以下代码:
public class tryClass
{
int[] v = {0}; // vector v is non-static (and NOT local to any method)
tryClass obj;
public void met ()
{
obj = new tryClass();
obj.v[0] = 30;
v[0]=3;
}
public static void main (String[] args)
{
tryClass obj = new tryClass(); // is this the SAME object as in met() ?
int[] v = new int[1];
obj.v[0] = 40;
obj.met();
}
}
为了了解每一步如何v
处理向量,我在代码中填写了一些println
指令,我的输出如下:
In main(), BEFORE running met()
obj.v[0] = 40
obj.v = [I@78456a0c
INSIDE method met()
obj.v[0] = 30
v[0] = 3
obj.v = [I@15357784
v = [I@78456a0c
In main(), AFTER running met()
obj.v[0] = 3
obj.v = [I@78456a0c
我对很多事情感到很困惑,首先是为什么静态方法中obj.v
调用时的引用与非静态方法内部的引用main()
相同。此外,在没有对象的情况下调用(当然是在非静态上下文中)究竟是什么?v
met()
v
我是Java新手,我真的有很多问题,我希望答案可以完全解决它们......提前感谢您的帮助。
为了完整起见,完整的代码是
public class tryClass
{
int[] v = {0};
tryClass obj;
public void met ()
{
obj = new tryClass();
obj.v[0] = 30;
v[0]=3;
System.out.println("\nINSIDE method met()");
System.out.println("\tobj.v[0] = "+obj.v[0]);
System.out.println("\tv[0] = "+v[0]);
System.out.println("\tobj.v = "+obj.v);
System.out.println("\tv = "+v);
}
public static void main (String[] args)
{
tryClass obj = new tryClass();
int[] v = new int[1];
obj.v[0] = 40;
System.out.println("In main(), BEFORE running met()");
System.out.println("\tobj.v[0] = "+obj.v[0]);
System.out.println("\tobj.v = "+obj.v);
obj.met();
System.out.println("\nIn main(), AFTER running met()");
System.out.println("\tobj.v[0] = "+obj.v[0]);
System.out.println("\tobj.v = "+obj.v);
}
}