简体   繁体   English

为什么println打印引用对象的值而不是对象地址

[英]Why does println print the value of a referenced object rather than the address of the object

String myString="Plz_help";

I came to know that 'myString' is not an object but a object reference variable which stores the base address of the actual object. 我知道'myString'不是对象,而是存储实际对象基址的对象引用变量。 So 'myString' should return an address when i execute 因此,“ myString”在执行时应返回一个地址

System.out.println(myString);

but it is returning 'Plz_help' to the output. 但是它将“ Plz_help”返回到输出。

Myclass obj_ref_var=new Myclass();

When I use the same System.out.println(obj_ref_var) for other class which I had created, it is returning the address. 当我对我创建的其他类使用相同的System.out.println(obj_ref_var)时,它将返回地址。

When you call System.out.println on an object reference, system executes toString() method defined for the actual object that this reference refers to. 当您在对象引用上调用System.out.println时,系统将执行为该引用所引用的实际对象定义的toString()方法。 For String this method returns its value. 对于String此方法返回其值。

Apparently, you haven't defined toString() method for your class that's why you get object classname + hashcode. 显然,您尚未为类定义toString()方法,这就是为什么要获取对象类名+哈希码的原因。

println knows about String s, and outputs their contents. println知道String ,并输出它们的内容。

When you pass something other than a String into println , it implicitly calls that thing's toString method. 当您将String以外的内容传递给println ,它将隐式调用该东西的toString方法。 The default toString on Object returns what you're seeing, which is not an address, but rather the name of the class, a @ , and the hex version of the object's hash code . Object的默认toString返回您所看到的内容,它不是地址,而是类的名称, @对象的哈希码十六进制版本

Well, System.out.println uses the reference to call the object's toString method. 好吧, System.out.println使用引用来调用对象的toString方法。

As the toString() method of string returns the string itself, this is what printed. 由于string的toString()方法将返回字符串本身,因此将显示此内容。

But since you haven't override the toString method of MyClass , it returns the default toString , which is classname + hashcode. 但是,由于尚未覆盖MyClasstoString方法,因此它将返回默认的toString ,即类名+哈希码。

When you System.out.println() an object, the println method checks if it's null and prints null if it is. 当您使用System.out.println()对象时,println方法将检查它是否为null,如果为null则将其输出。 If it isn't null, it calls the toString() method of the object. 如果不为null,则调用对象的toString()方法。 The toString() method of String overrides the Object.toString() method, to return itself. StringtoString()方法将覆盖Object.toString()方法以返回自身。

Anyway, System.out.println() doesn't print the reference, it prints the object itself. 无论如何, System.out.println()不会打印引用,而是打印对象本身。 The Object's implementation of toString() returns the class name of the object followed by its hashCode. Object的toString()实现返回对象的类名,后跟其hashCode。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM