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
2.在容器类中使用toString()
编写一个工具类,用于在控制台输出Iterator。
import java.util.Iterator;
public class Printer {
static void printAll(Iterator e){
while(e.hasNext()){
System.out.println(e.next());
}
}
}
在Hamster类中重写父类的toString()方法。
public class Hamster {
private int hamsterNumber;
public Hamster(int hamsterNumber){
this.hamsterNumber=hamsterNumber;
}
public String toString(){
return "This is Hamster #"+hamsterNumber;
}
}
public class HamsterMaze {
@SuppressWarnings("unchecked")
public static void main(String[] args){
List list=new ArrayList();
for(int i=0;i<3;i++)
list.add(new Hamster(i));
Printer.printAll(list.iterator());
}
}
结果:
This is Hamster #0
This is Hamster #1
This is Hamster #2