【java】打印一個對象即打印出該對象toString()返回值


 1 public class TestToString {
 2     public static void main(String[] args){
 3         Node node1=new Node("東邪");
 4         node1.next=new Node("西毒");
 5         node1.next.next=new Node("南帝");
 6         node1.next.next.next=new Node("北丐");
 7         node1.next.next.next.next=new Node("中神通");
 8         System.out.println(node1);//打印一個對象即調用該對象的toString()並打印出toString()返回值
 9     }
10 }
11 class Node{
12     Object value;
13     Node next;
14     public Node(Object value){
15         this.value=value;        
16     }
17     public String toString(){
18         return next==null?value.toString():value+","+next;//對象和String類型作+操作是返回對象的toString
19     }
20 }
View Code

運行結果:

東邪,西毒,南帝,北丐,中神通


免責聲明!

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



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