【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