为什么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;
}
}
这是我得到的输出
in has 5
in has 5
2.5
6.0
more has 3
word
System.out.println
方法不知道如何输出自定义类型的实例,因此,它可以做的下一件事是调用toString
方法,该方法可用于Java中的所有对象并返回字符串表示形式。在这种情况下,您已重写它,因此它实际上执行您的toString
方法并打印结果。