打印对象的引用

我是java的新手。 说,我有一个class级个人 。 我想要打印

Individual ind = new Individual(); System.out.println(ind); 

上面的代码给出了这样的输出:

 Individual@1922221 
  1. 这有什么意义?
  2. 它是该对象的某种唯一ID吗?
  3. 我可以自定义吗? 我的意思是写一个我自己的函数,当我打印时会给出输出?
  4. 如果是这样,我该怎么做?

如果要打印任何对象的有意义内容,则必须实现自己的toString()方法,该方法将覆盖父( Object )类的toString()方法。 默认情况下,所有类(无论您创建什么)都扩展了Object类。

示例代码:

 public class Individual { private String name; private String city; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Name of Individual :").append(this.getName()) .append("\nCity :").append(this.getCity()); return builder.toString(); } public static void main(String[] args) { Individual individual = new Individual(); individual.setName("Crucified Soul"); individual.setCity("City of Crucified Soul"); System.out.println(individual); } } 

输出:

 Name of Individual :Crucified Soul City :City of Crucified Soul 

如果你有一个包含许多变量的更大的类,你可以使用XStream来实现你的toString()方法。 XStream将以XML格式打印有意义的对象。 即使您可以将它们解析回等效对象。 希望这会对你有所帮助。

这是默认的toString()方法的结果 – 类名+哈希码。 这可以通过覆盖toString()来覆盖。

这里有一些参考: http : //www.javapractices.com/topic/TopicAction.do?Id=55

由于尚未解释,覆盖toString()方法只是意味着您在类中创建自己的toString()方法。 通过在类中放置自己的toString()版本,可以使java使用toString()方法而不是默认方法。 但是,因为原始的toString()方法返回一个字符串,所以你的toString()方法也必须返回一个字符串。 你的个人课程看起来像这样:

 public class Individual{ //any other code in the class public String toString(){ return "your string"; } } 

然后,当你调用System.out.print(ind)时; 它会打印出你的字符串。

我想你想覆盖个人toString。 请参阅http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#toString ()