自己(轉)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 }
 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM