/*
*WorksAnyway.java
*in special cases,things just seem to work correctly.
*/
class Mouse{
private int mouseNumber;
Mouse(int i){
mouseNumber=i;
}
}
void print(String msg){
if(msg!=null)
System.out.println(msg);
System.out.println("mouse number "+mouseNumber);
}
}
class MouseTrap{
static void caughtYa(Object m){ //使用这个函数时 无需进行造型m
Mouse mouse=(Mouse)m; //
mouse.print("Caught one!");
}
}
public class TomAndJerry{
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<mice.size();i++){
//no cast necessary ,automatic call
//to Object.String
System.out.println(
"free mouse:"+mice.elementAt(i)); @1
MouseTrap.caughtYa(mice.elementAt(i));
}
}
*WorksAnyway.java
*in special cases,things just seem to work correctly.
*/
class Mouse{
private int mouseNumber;
Mouse(int i){
mouseNumber=i;
}
//magic method:
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){ //使用这个函数时 无需进行造型m
Mouse mouse=(Mouse)m; //
mouse.print("Caught one!");
}
}
public class TomAndJerry{
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<mice.size();i++){
//no cast necessary ,automatic call
//to Object.String
System.out.println(
"free mouse:"+mice.elementAt(i)); @1
MouseTrap.caughtYa(mice.elementAt(i));
}
}
}
隐藏造型1:一个是在magic method哪儿,@1出用到;另一个是在caughtYa方法中,通过Object, 强制造型,但这样很危险。