java打印和重写toString

[java] view plain copy
  1.    
  2. class Person  
  3. {  
  4.     private String name;  
  5.     public Person(String name)  
  6.     {  
  7.         this.name=name;  
  8.     }  
  9. }  
  10. public classPrintObject {  
  11.     public static voidmain(String[] args)  
  12.     {  
  13.         Person2 p=new Person("ping");  
  14.         System.out.println(p.toString());  
  15.     }  
  16.    
  17. }  


上面程序创建了一个Person对象,然后使用System.out.println()方法输出Person对象,结果如下:

Person@15db9742

System.out的println方法只能在控制台输出字符串,而Person实例是一个内存中的对象,怎么能直接转换为字符串输入呢?当使用该方法输出Person对象时,实际上输出Person对象的toString()方法的返回值,也就是这面代码效果相同

System.out.println(p);

System.out.println(p.toString());

toString方法是Object类里的一个实例方法,所有Java类都是object类的子类,因此所有Java对象都具有toString方法。

不仅如此,所有Java对象都可以和字符串进行连接运算,当Java对象和字符串进行连接运算时,系统自动调用Java对象toString()方法返回值和字符串进行连接运算下面代码效果相同

String pStr=p+””;

StringpStr=p.toString()+””;

  toString()方法是一个非常特殊的方法,是一个“自我描述”方法,该方法通常用于实现当程序员直接打印该对象时,系统将会输出该对象的“自我描述”信息,用以告诉外界该对象具有的状态信息。

  Object类提供的toString()方法总是返回该对象实现类的”类名+@+hashCode”值,这个返回值不能真正实现“自我描述”功能,因此我们可以重写object的toString()方法。

 

[java] view plain copy
  1. class Apple1  
  2. {  
  3.     private String color;  
  4.     private double weight;  
  5.     public Apple1(String color,double weight)  
  6.     {  
  7.         this.color=color;  
  8.         this.weight=weight;  
  9.     }  
  10.    
  11. public StringtoString()  
  12. {  
  13.     return "Apple["+color+",weight:"+weight+"]";  
  14. }  
  15. }  
  16.    
  17. public classToStringTest {  
  18.     public static voidmain(String[] args)  
  19.     {  
  20.     Apple1 a=new Apple1("红色"5.68);  
  21.     System.out.println(a);  
  22.     }  
  23.      
  24.      
  25.      
  26. }  


运行结果

Apple[color=红色,weight=5.68]

原文地址:https://www.cnblogs.com/jinhengyu/p/10258085.html