I am learning java, and studying the following example from sun.com.
import java.io.*;
import java.util.*;
public class UserInfo implements Serializable {
String name = null;
public UserInfo(String name) {
this.name = name;
}
public void printInfo() {
System.out.println("The name is: "+name);
}
}
import java.io.*;
import java.util.Date;
public class ReadInfo {
public static void main(String argv[]) throws Exception {
FileInputStream fis = new FileInputStream("name.out");
ObjectInputStream ois = new ObjectInputStream(fis);
UserInfo user1 = (UserInfo) ois.readObject();
UserInfo user2 = (UserInfo) ois.readObject();
user1.printInfo();
user2.printInfo();
ois.close();
fis.close();
}
}
I am having question regarding the ReadInfo.java. In specific, I do not know how to understand the code of line UserInfo user1 = (UserInfo) ois.readObject(); Especially, what is the functionality of “UserInfo” in the parenthesis. What is the relationship between (UserInfo) and ols.readObject( ).
The Object is being read and the code is casting it to a UserInfo Object, as there is some knowledge by the code author that “name.out” contains serialized Objects of type UserInfo.
The API makes this very clear:
Additionally you might want to read up on the Java tutorial’s section re: Casting Objects.