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 }
运行结果:
东邪,西毒,南帝,北丐,中神通