JAVA toString方法

來源:互聯網
上載者:User

標籤:

在JAVA中,所有的對象都有toString方法;

建立類時沒有定義toString方法,輸出對象時,會輸出對象的雜湊值;

它只是sun公司開發java的時候為了方便所有類的字串操作而特意加入的一個方法

它通常只是為了方便輸出:

例如:

public class Test2{    String name;    int age;    public String toString(){        return "我的姓名是:"+name+"\t我的年齡是:"+age;    }    public static void main(String[] args){        Test2 Myclass    =    new    Test2();        Myclass.name    =    "小明";        Myclass.age        =    20;        System.out.println(Myclass);    //直接使用對象名時預設調用該對象的toString方法        System.out.println(Myclass.toString());//手動調用String方法    }}

 

運行結果:

 

如果類中沒有定義toString方法,按照以上案例調用時,會輸出對象的雜湊值,如下案例所示:

public class Test2{    String name;    int age;    /*public String toString(){        return "我的姓名是:"+name+"\t我的年齡是:"+age;    }*/    public static void main(String[] args){        Test2 Myclass    =    new    Test2();        Myclass.name    =    "小明";        Myclass.age        =    20;        System.out.println(Myclass);    //直接使用對象名時預設調用該對象的toString方法        System.out.println(Myclass.toString());//手動調用String方法即便toString方法沒有定義,也可以調用,因為所有對象預設都有toString方法    }}

運行結果:

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.