在用java语言编程时如果能更了解其特性,对代码的灵活性提升无疑是有帮助的。出于这个目的做了一个测试并将其记录在这里,以供以后查看(jdk1.7)。
1、测试代码
package pers.shenshiheng.test.serializable; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class SerializableTest { public static void main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\temp.out"); ObjectOutputStream oos = new ObjectOutputStream(fos); Son son = new Son(); oos.writeObject(son); oos.flush(); oos.close(); FileInputStream fis = new FileInputStream("C:\\Users\\Lenovo\\Desktop\\temp.out"); ObjectInputStream ois = new ObjectInputStream(fis); Parent deParent = (Parent) ois.readObject(); System.out.println(deParent.getClass()); System.out.println(deParent.getValue()); System.out.println(deParent.getSameField()); System.out.println(deParent.parentValue); System.out.println(deParent.sameField); System.out.println("----------------------"); Son deSon = (Son) deParent; System.out.println(deSon.getClass()); System.out.println(deSon.getValue()); System.out.println(deSon.getSameField()); System.out.println(deSon.parentValue); System.out.println(deSon.sameField); System.out.println("----------------------"); System.out.println(deSon.sonValue); System.out.println(deSon.innerObject.innerValue); System.out.println("----------------------"); System.out.println(Ancestor.value); } } interface Ancestor{ public String value = "ancestorValue"; } class Parent implements Serializable,Ancestor { private static final long serialVersionUID = -4963266899668807475L; public String sameField = "ParentSameField"; public String parentValue = "parentValue"; public String getValue(){ return parentValue; } public String getSameField(){ return sameField; } } class InnerObject implements Serializable { private static final long serialVersionUID = 5704957411985783570L; public String innerValue = "innerValue"; } class Son extends Parent implements Serializable { private static final long serialVersionUID = -3186721026267206914L; public String sameField = "SonSameField"; public String sonValue = "sonValue"; public InnerObject innerObject = new InnerObject(); public String getValue(){ return sonValue; } public String getSameField(){ return sameField; } }
2、输出结果
class pers.shenshiheng.test.serializable.Son
sonValue
SonSameField
parentValue
ParentSameField
----------------------
class pers.shenshiheng.test.serializable.Son
sonValue
SonSameField
parentValue
SonSameField
----------------------
sonValue
innerValue
----------------------
ancestorValue
3、结论
接口里面无论你怎么声明只能存在静态常量,获取类的话是返回实际对象的类,相同方法名时调用实际对象的方法,子类可以直接获取父类的属性,在反序列化之后依然保持有引用对象的存在,获取属性名相同的属性时 会获取到引用对象的属性值,在实际对象方法内调用相同属性名的属性时获取到的是实际对象的属性值。
Parent parent = new Son();
parent :引用对象
new Son():实际对象