重写toSting()方法

import java.util.Vector;


class Mouse{
private int mouseNumber;
Mouse(int i){
mouseNumber = i;
}
public String toString(){
return "This is Mouse #" + mouseNumber;
}
void print(String msg){
if(msg != null){
System.out.println(msg);
}
System.out.println("Mouse number = " + mouseNumber);
}
}


class MouseTrap{
static void caughtYa(Object m){
Mouse mouse = (Mouse)m;
mouse.print("Caught one!");
}
}
public class WorksAnyway{
public static void main(String[] args) {
Vector mice = new Vector();
for(int i=0; i<3; i++){
mice.addElement(new Mouse(i));
}
for(int i=0; i System.out.println("Free mouse: " + mice.elementAt(i));
MouseTrap.caughtYa(mice.elementAt(i));
}
}

}

结果:

Free mouse: This is Mouse #0
Caught one!
Mouse number = 0
Free mouse: This is Mouse #1
Caught one!
Mouse number = 1
Free mouse: This is Mouse #2
Caught one!
Mouse number = 2

在“+”后,编译器预期看到的是一个String对象,elementAt()生成了一个Object,所以为获得希望的String,编译器会默认调用toStirng()。

你可能感兴趣的:(java基础知识)