java中的字符串引用

Eig*_*ght 0 java string reference

class test
{
    public static void main(String args[])
    {
        test ob=new test();
        String st=new String("it is a string");

        System.out.println(ob);
    System.out.println(st);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此代码中,ob是测试类的引用,st是字符串类的引用.虽然打印ob显示引用但st打印值,即"它是一个字符串"..为什么?

Bri*_*ach 7

因为你没有toString()在你的test类中重写,所以它使用了来自Object(java中所有对象的父类)的那个,它只是输出类名和哈希码.

Josh Bloch在"Effective Java"中概述了这一点:

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

(参见:"第9项:始终覆盖toString")


sus*_*ani 6

因为string类重写了一个类的方法toString,Object该方法应该打印传递给构造函数的内容.但是测试类不会这样做.