所有java的类的父类是java.lang,在这个类里面有一个tostring函数是用来显示一些关于这个对象的hashcode等相关信息,当你要显示一个对象的时候,系统会自动调用这个对象的tostring方法,而它显示的都是一些系统数据,例如hashcode。如果你想显示你想要的东西,那么就应该重写这个类,把这个函数给覆盖了,那么系统就会调用你写的tostring方法,可以显示你想要的方法.
看如下代码:
package sample;
class Villain {
private String name;
protected void set(String nm) {
name = nm;
}
public Villain(String name) {
this.name = name;
}
public String toString() {
return "I'm a Villain and my name is " + name;
}
}
public class Orc extends Villain {
private int orcNumber;
public Orc(String name, int orcNumber) {
super(name);
this.orcNumber = orcNumber;
}
public void change(String name, int orcNumber) {
set(name);
this.orcNumber = orcNumber;
}
public String toString() {
return "Orc" + orcNumber + ":" + super.toString();
}
public static void main(String[] args) {
Orc orc = new Orc("Limburger", 12);
System.out.println(orc);
orc.change("Bob", 19);
System.out.println(orc);
}
}
结果:
sample.Orc@11b86e7
sample.Orc@11b86e7
如果去掉注释,即加入2个toString()方法后,得到
结果:
Orc12:I'm a Villain and my name is Limburger
Orc19:I'm a Villain and my name is Bob
|