自己(转)JAVA中toString方法的作用

2022-12-31,,,

JAVA中toString方法作用

因为它是Object里面已经有了的方法,而所有类都是继承Object,所以“所有对象都有这个方法”。

它通常只是为了方便输出,比如System.out.println(xx),括号里面的“xx”如果不是String类型的话,就自动调用xx的toString()方法

总而言之,它只是sun公司开发java的时候为了方便所有类的字符串操作而特意加入的一个方法

回答补充:

写这个方法的用途就是为了方便操作,所以在文件操作里面可用可不用

例子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”之类的输出方法时会自动调用,不用显式打出来。

 

 

 1 public class Zhang
2
3 {
4
5 public static void main(String[] args)
6
7 {
8
9 StringBuffer MyStrBuff1 = new StringBuffer();
10
11 MyStrBuff1.append("Hello, Guys!");
12
13 System.out.println(MyStrBuff1.toString());
14
15 MyStrBuff1.insert(6, 30);
16
17 System.out.println(MyStrBuff1.toString());
18
19 }
20
21 }

 

值得注意的是, 若希望将StringBuffer在屏幕上显示出来, 则必须首先调用toString方法把它变成字符串常量,因为PrintStream的方法println()不接受StringBuffer类型的参数.

 

1 public class Zhang
2 {
3 public static void main(String[] args)
4 {
5 String MyStr = new StringBuffer();
6 MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString();
7 System.out.println(MyStr);
8 }
9 }

 

toString()方法在此的作用是将StringBuffer类型转换为String类型.

 

1 public class Zhang
2 {
3 public static void main(String[] args)
4 {
5 String MyStr = new StringBuffer().append("hello").toString();
6 MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString();
7 System.out.println(MyStr);
8 }
9 }

 

自己(转)JAVA中toString方法的作用的相关教程结束。

《自己(转)JAVA中toString方法的作用.doc》

下载本文的Word格式文档,以方便收藏与打印。