【问题标题】:Parent class Constructor父类构造函数
【发布时间】:2015-08-17 10:12:45
【问题描述】:
public class Parent {

public Parent() {

System.out.println("Parent");

    }
}


public class Child extends Parent implements Serializable {


  public Child() {

      System.out.println("Child");
    }

}

public class Demote {

    public static void main(String[] args) {
      Child c=new Child();
       try {
        FileOutputStream fos=new FileOutputStream   
                                        ("D:\\DemoFile\\Testword5.txt");

        ObjectOutputStream oot=new ObjectOutputStream(fos);
        oot.writeObject(c);
        FileInputStream fin=new FileInputStream 
                                      ("D:\\DemoFile\\Testword5.txt");

        ObjectInputStream oin=new ObjectInputStream(fin);
        oin.readObject();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch (IOException e) {
        e.printStackTrace();
    }catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    }
 }

此代码的输出是 - Parent Child Parent。

调用第一个集合 Parent Child 是因为调用了零参数构造函数。 oin.readObject() 正在返回一个子对象。那为什么只调用父类的构造函数,为什么不调用子类

【问题讨论】:

标签: java


【解决方案1】:

调用 Parent 构造函数是因为它没有实现 Serializable。然而,Child 确实实现了 Serializable,但不会调用它。

【讨论】:

  • 您能详细说明为什么这样做有意义吗?我的意思是考虑到你已经告诉过它为什么这样工作的问题,但是这个设计决定背后的原因是什么,为什么它应该这样工作。有什么想法吗?
  • @AseemBansal 父类无法知道子类已被标记为可序列化。所以它是通过构造函数以正常方式初始化的。然而子类知道构造函数不需要被调用,因为它是可序列化的。
【解决方案2】:

引用The Java Docs for Serializable:

为了允许序列化不可序列化类的子类型,子类型可能会负责保存和恢复超类型的公共、受保护和(如果可访问)包字段的状态。只有当它扩展的类具有可访问的无参数构造函数来初始化类的状态时,子类型才可以承担此责任。如果不是这种情况,则声明类 Serializable 是错误的。将在运行时检测到错误。

在反序列化期间,不可序列化类的字段将使用类的公共或受保护的无参数构造函数进行初始化。可序列化的子类必须可以访问无参数构造函数。可序列化子类的字段将从流中恢复。

Serializable 类本身不需要无参数构造函数,如果存在,则不会用于初始化它们。

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2014-12-16
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多