日期:2014-05-20  浏览次数:20763 次

为什么能调用这个方法啊?谢谢
import java.io.*;

public class User implements Serializable {
private String name;
private transient String password;
public User(String name,String password){
this.name =name;
this.password =password;
}
public String toString(){
return name+" "+password;
}
private byte[] change(byte[] buff){
//加密数组
}
private void writeObject(ObjectOutputStream stream)throws IOException{
stream.defaultWriteObject();
stream.writeObject(change(password.getBytes()));
}
private void readObject(ObjectInputStream stream)throws IOException,ClassNotFoundException{
stream.defaultReadObject();
byte[] buff=(byte[])stream.readObject();
password=new String(change(buff));
}
public static void main(String[] args)throws Exception {
User user=new User("Tom","12345");
System.out.println("Before Serialization:"+user);
ByteArrayOutputStream buf=new ByteArrayOutputStream();

ObjectOutputStream o=new ObjectOutputStream(buf);
o.writeObject(user);

ObjectInputStream in=new ObjectInputStream(
new ByteArrayInputStream(buf.toByteArray()));
user=(User)in.readObject();
System.out.println("After Serialization:"+user);
}
}

上述代码中o.writeObject(user),为什么o能调用User类中定义的方法,而且参数也不对应

------解决方案--------------------
楼上说得也不是很准确,应该说ObjectOutputStream本身含有writeObejct(Obejct ojb)方法,同时也允许程序员对这个方法进行重写,所以程序中调用的writeObject()方法是重写后的方法