[英]Why does the "this" keyword print exactly what toString() is printing?
Why does the this
keyword print exactly what the toString
method is printing?为什么
this
关键字打印的正是toString
方法打印的内容?
public class A {
public static void main(String[] args) {
Stuff s = new Stuff("in",5 );
System.out.println(s);
double doubleValue = 2.5 ;
s.doSomething(doubleValue);
System.out.println(doubleValue);
s = new Stuff("more", 3);
String str = "word";
System.out.println(s.changeSomething(str));
System.out.println(s);
System.out.println(str);
}
}
class Stuff {
private static final int n =2 ;
private String string;
private int num;
public Stuff(String s, int num) {
this.num = num;
string = s;
}
public void doSomething(double d) {
d = d * num;
System.out.println(this);
}
public double changeSomething(String s) {
s = string;
return n * num;
}
public String toString() {
return string + " has " + num;
}
}
This is the output I get这是我得到的输出
in has 5
in has 5
2.5
6.0
more has 3
word
System.out.println
method does not know how to output an instance of a custom type, so the next best thing it can do is to call the toString
method, which is available on all objects in Java and returns the string representation. System.out.println
方法不知道如何输出自定义类型的实例,因此它可以做的下一个最好的事情是调用toString
方法,该方法可用于 Java 中的所有对象并返回字符串表示形式。 In this case you have overridden it, so it actually executes your toString
method and prints the result.在这种情况下,您已经覆盖了它,因此它实际上会执行您的
toString
方法并打印结果。
You can read the documentation of System.out.println()
.您可以阅读
System.out.println()
的文档。 System.out
is a PrintStream
. System.out
是一个PrintStream
。 PrintStream::println(Object)
calls PrintStream::print(Object)
, which calls String.valueOf(Object)
, which returns the string "null"
if the reference is null; PrintStream::println(Object)
调用PrintStream::print(Object)
,后者调用String.valueOf(Object)
,如果引用为空,则返回字符串"null"
; otherwise returns obj.toString()
.否则返回
obj.toString()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.