java 继承 序列化_带继承的序列化(Java)

我正在学习序列化和继承,并且我不了解谁在反序列化过程中调用了no-arg构造函数.超类A不实现Serializable,而子类B扩展A实现Serializable.

超类A

public class A {

int i;

public A(int i)

{

this.i = i;

}

public A()

{

i = 50;

System.out.println("A's class constructor called");

}

}

B类

import java.io.Serializable;

public class B extends A implements Serializable {

int j;

// parameterized constructor

public B(int i,int j)

{

super(i);

this.j = j;

}

}

驾驶员等级

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

public class Test {

public static void main(String[] args) throws Exception {

B b1 = new B(10,20);

System.out.println("i = " + b1.i);

System.out.println("j = " + b1.j);

// Serializing B's(subclass) object

//Saving of object in a file

FileOutputStream fos = new FileOutputStream("abc.ser");

ObjectOutputStream oos = new ObjectOutputStream(fos);

// Method for serialization of B's class object

oos.writeObject(b1);

// closing streams

oos.close();

fos.close();

System.out.println("Object has been serialized");

// De-Serializing B's(subclass) object

// Reading the object from a file

FileInputStream fis = new FileInputStream("abc.ser");

ObjectInputStream ois = new ObjectInputStream(fis);

// Method for de-serialization of B's class object

B b2 = (B)ois.readObject(); // The A() constructor is called here

// closing streams

ois.close();

fis.close();

System.out.println("Object has been deserialized");

System.out.println("i = " + b2.i);

System.out.println("j = " + b2.j);

}

}

如果删除A()构造函数,则会收到InvalidClassException.我看到在创建b2对象时调用了A(),但我不明白为什么在此语句中调用此A()以及调用它的人.

创建b1对象时,将调用B(int i,int j)构造函数以及A(int i)构造函数.这很容易理解.但是我不明白为什么在创建b2对象时调用A()构造函数.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值