toStrig方法
toString()方法返回反映这个对象的字符串,因为toString方法是Object里面已经有了的方法,而所有类都是继承Object,所以“所有对象都有这个方法”。
它通常只是为了方便输出,比如System.out.println(xx),括号里面的“xx”如果不是String类型的话,就自动调用xx的toString()方法
总而言之,它是为了方便所有类的字符串操作而特意加入的一个方法,字符串内容就是对象的类型+@+内存地址值
由于toString方法返回的结果是内存地址,而在开发中,经常需要按照对象的属性得到相应的字符串表现形式,因此也需要重写它。
class Person extends Object{ int age ; //根据Person类的属性重写toString方法 public String toString() { return "Person [age=" + age + "]"; } }
例子1:
public class Orc { public static class A { public String toString() { return "this is A"; } } public static void main(String[] args) { A obj = new A(); System.out.println(obj); } }
如果某个方法里面有如下句子:
A obj=new A();
System.out.println(obj);
会得到输出:this is A
例子2:
public class Orc { public static class A { public String getString() { return "this is A"; } } public static void main(String[] args) { A obj = new A(); System.out.println(obj); System.out.println(obj.getString()); } }
会得到输出:xxxx@xxxxxxx的类名加地址形式
System.out.println(obj.getString());
会得到输出:this is A
区别在于,toString的好处是在碰到“println”之类的输出方法时会自动调用,不用显式打出来。
例子3:
值得注意的是, 若希望将StringBuffer在屏幕上显示出来, 则必须首先调用toString方法把它变成字符串常量, 因为PrintStream的方法println()不接受StringBuffer类型的参数.
public class Zhang { public static void main(String[] args) { StringBuffer MyStrBuff1 = new StringBuffer(); MyStrBuff1.append("Hello, Guys!"); System.out.println(MyStrBuff1.toString()); MyStrBuff1.insert(6, 30); System.out.println(MyStrBuff1.toString()); } }
toString()方法在此的作用是将StringBuffer类型转换为String类型.
public class Zhang { public static void main(String[] args) { String MyStr = new StringBuffer().append("hello").toString(); MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString(); System.out.println(MyStr); } }