返回值,进一步解释

Edi*_*Edi 0 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 samplethis();
        cal.sample();// return samplethis@1718c21
    }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道它为什么会回来samplethis@1718c21?

Jon*_*eet 7

您的代码不会返回任何内容 - 它会打印调用的结果this.toString().

除非你被覆盖Object.toString(),否则你会得到默认的实现:

类Object的toString方法返回一个字符串,该字符串由对象为实例的类的名称,符号字符"@"和对象的哈希码的无符号十六进制表示组成.换句话说,此方法返回一个等于值的字符串:

getClass().getName() + '@' + Integer.toHexString(hashCode())
Run Code Online (Sandbox Code Playgroud)

具有散列码有可以更容易地发现可能等于同一个对象的引用.如果你写:

Foo foo1 = getFooFromSomewhere();
Foo foo2 = getFooFromSomewhere();
System.out.println("foo1 = " + foo1);
System.out.println("foo2 = " + foo2);
Run Code Online (Sandbox Code Playgroud)

其结果是相同的,那么foo1和foo2可能指向同一个对象.它不能保证,但它至少是一个很好的指标 - 而且这种字符串形式实际上只对诊断有用.

如果你想让你的代码打印出更有用的东西,你需要覆盖toString,例如(in samplethis)

@Override
public String toString() {
    return String.format("samplethis {a=%d; b=%d; c=%s}", a, b, c);
}
Run Code Online (Sandbox Code Playgroud)