Java 此项的返回值,请进一步说明
我编写了以下代码:Java 此项的返回值,请进一步说明,java,this,Java,This,我编写了以下代码: 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
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(),否则您将得到:
class对象的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
)
谢谢,非常有用,我明白你的意思了,所以当我想知道“this”指的是哪个对象时,默认的toString()方法非常有用
@Override
public String toString() {
return String.format("samplethis {a=%d; b=%d; c=%s}", a, b, c);
}