public class Box {
int height;
int length;
int width;
}
public class Volume {
public static void main(String args[]){
Box mybox = new Box();
Box mybox1= mybox;
Box mybox2 = new Box();
System.out.println(" The address of the mybox object is:"+System.identityHashCode(mybox));
System.out.println(" The value of the mybox object is:"+mybox);
System.out.println(" The address of the object mybox1 is :"+ System.identityHashCode(mybox1));
System.out.println(" The value of the mybox1 object is:"+mybox1);
System.out.println(" The address of the object mybox2 is :"+ System.identityHashCode(mybox2));
System.out.println(" The value of the mybox2 object is:"+mybox2);
}
}
这个程序的目标是帮助我理解 Java 中对象创建和内存分配的概念。根据我的理解,new运算符应该为对象创建一个内存并返回存储在内存中的引用。为了获取对象的地址,我使用 System.identityHashCode 函数。为了获取存储在该内存地址中的引用的值,我直接打印该对象。下面我们可以看到结果。
The address of the mybox object is:1956725890
The value of the mybox object is:Box@74a14482
The address of the object mybox1 is :1956725890
The value of the mybox1 object is:Box@74a14482
The address of the object mybox2 is :356573597
The value of the mybox2 object is:Box@1540e19d
根据上述结果,我的理解是 mybox 和 mybox1 将具有相同的地址,并且它们将在该地址中携带相同的引用值,因为 mybox1 未实例化并被分配给 mybox。 mybox2 将有一个新地址,并且该地址中将有一个新的引用值。
所以我的问题是
如果没有实例化,mybox1 如何拥有地址以及该地址中的引用?
Java完整引用这本书确实提到,每个对象实例化后都会保存实际对象Box的内存地址。那么为什么mybox2中存储的引用值与存储的引用值不同呢在我的盒子里?我假设只需打印变量,它就会给我存储在该变量中的值,这是对对象 Box 的引用。
感谢大家提供的任何建议,可以帮助我理解 java 的基本概念。我是一名新手,我非常感谢 stackoverflow 成员传播的丰富知识。
最佳答案
a) 线路Box mybox1= mybox;
使变量 mybox1
指向 mybox
创建的对象多变的。因此,两个变量 mybox
和mybox1
指向同一个对象。请注意new
运算符在前两行中仅使用一次。
b) 由于您正在为 mybox2
创建一个新对象在线Box mybox2 = new Box();
,它将在堆中创建一个全新的对象。变量的值mybox
和mybox2
您看到的基本上是类的名称,后跟十六进制格式的对象的哈希码。
当您打印变量 mybox
时使用System.out.println()
它在内部执行 toString 方法:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
关于java - Java中如何获取类的对象的引用值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34610573/