JAVA中toString方法

來源:互聯網
上載者:User

標籤:

因為它是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());

}

}

會得到輸出:[email protected]的類名加地址形式

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方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.