国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

談談J2SE中的序列化之當序列化遭遇繼承

2019-11-17 06:20:38
字體:
來源:轉載
供稿:網友
  當一個父類實現Serializable接口后,他的子類都將自動的實現序列化。

  以下驗證了這一點:

package Serial;
import java.io.Serializable;
public class SuperC implements Serializable {//父類實現了序列化
 int supervalue;
 public SuperC(int supervalue) {
  this.supervalue = supervalue;
 }
 public String toString() {
  return "supervalue: "+supervalue;
 }
}

public class SubC extends SuperC {//子類
 int subvalue;

 public SubC(int supervalue,int subvalue) {
  super(supervalue);
  this.subvalue=subvalue;
 }

 public String toString() {
  return super.toString()+" sub: "+subvalue;
 }
}

public class Test1 {

 public static void main(String [] args){
  SubC subc=new SubC(100,200);
  FileInputStream in=null;
  FileOutputStream out=null;
  ObjectInputStream oin=null;
  ObjectOutputStream oout=null;
  try {
   out = new FileOutputStream("Test1.txt");//子類序列化
   oout = new ObjectOutputStream(out);
   oout.writeObject(subc);
   oout.close();
   oout=null;

   in = new FileInputStream("Test1.txt");
   oin = new ObjectInputStream(in);
   SubC subc2=(SubC)oin.readObject();//子類反序列化
   System.out.PRintln(subc2);
  } catch (Exception ex){
   ex.printStackTrace();
  } finally{
  …此處省略
 }
}
}
  運行結果如下:

supervalue: 100 sub: 200
  可見子類成功的序列化/反序列化了。

  怎管讓子類實現序列化看起來是一件很簡單的事情,但有的時候,往往我們不能夠讓父類實現Serializable接口,原因是有時候父類是抽象的(這并沒有關系),并且父類不能夠強制每個子類都擁有序列化的能力。換句話說父類設計的目的僅僅是為了被繼續。

  要為一個沒有實現Serializable接口的父類,編寫一個能夠序列化的子類是一件很麻煩的事情。java docs中提到:

“To allow suBTypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constrUCtor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. ”
  也就是說,要為一個沒有實現Serializable接口的父類,編寫一個能夠序列化的子類要做兩件事情:

  其一、父類要有一個無參的constructor;

  其二、子類要負責序列化(反序列化)父類的域。

  我們將SuperC的Serializable接口去掉,而給SubC加上Serializable接口。運行后產生錯誤:

java.lang.Error: Unresolved compilation problem:
Serializable cannot be resolved or is not a valid superinterface
at Serial.SubC.<init>(SubC.java:15)
at Serial.Test1.main(Test1.java:19)
Exception in thread "main"


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 保康县| 佛冈县| 吉林市| 全椒县| 丽江市| 金堂县| 方正县| 利津县| 增城市| 雅安市| 班戈县| 荥经县| 高平市| 漠河县| 定州市| 潍坊市| 游戏| 象州县| 双辽市| 双牌县| 石嘴山市| 甘洛县| 长汀县| 德阳市| 台中县| 乌兰察布市| 措美县| 河源市| 中方县| 阳城县| 前郭尔| 延长县| 惠州市| 靖安县| 云安县| 临夏市| 游戏| 翁牛特旗| 禄丰县| 金堂县| 会昌县|