【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

运行结果:

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

posted @ 2017-03-23 21:40  xiongjiawei  阅读(1940)  评论(0编辑  收藏  举报