我写了以下代码:
class samplethis {
int a = 6;
int b = 7;
String c = "i am";
public void sample() {
System.out.println(this);
}
}
public class thiss {
public static void main(String[] args) {
samplethis cal = new samplethis();
cal.sample();// return samplethis@1718c21
}
}
有人知道它为什么返回samplethis@1718c21
吗?
您的代码不会返回任何东西-它会打印调用this.toString()
的结果。
除非您覆盖了Object.toString()
,否则您将获得默认的实现:
Object类的toString方法返回一个字符串,该字符串由对象是其实例的类的名称、at符号字符"@"和对象哈希代码的无符号十六进制表示组成。换句话说,此方法返回一个等于以下值的字符串:
getClass().getName() + '@' + Integer.toHexString(hashCode())
有了散列代码,可以更容易地发现对同一对象的引用可能相等。如果你写:
Foo foo1 = getFooFromSomewhere();
Foo foo2 = getFooFromSomewhere();
System.out.println("foo1 = " + foo1);
System.out.println("foo2 = " + foo2);
则foo1
和foo2
可能引用相同的对象。这并不能保证,但它至少是一个很好的指示器,而且这种字符串形式实际上只对诊断有用。
如果你想让你的代码打印更有用,你需要覆盖toString
,例如(在samplethis
中)
@Override
public String toString() {
return String.format("samplethis {a=%d; b=%d; c=%s}", a, b, c);
}