无法理解以下Java代码的输出

时间:2019-06-25 17:22:19

标签: java inheritance serialization io

下面的代码返回“ pcp”,我不明白最后一个字符“ p”是如何打印的。换句话说,在反序列化过程中,父类构造函数如何运行以及子类构造函数为何不运行。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Player {
    Player() {
        System.out.print("p");
    }
}

public class CardPlayer extends Player implements Serializable {

    CardPlayer() {
        System.out.print("c");
    }

    public static void main(String[] args) {
        CardPlayer c1 = new CardPlayer();
        try {
            FileOutputStream fos = new FileOutputStream("play.txt");
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(c1);
            os.close();
            FileInputStream fis = new FileInputStream("play.txt");
            ObjectInputStream is = new ObjectInputStream(fis);
            CardPlayer c2 = (CardPlayer) is.readObject();
            is.close();
        } catch(Exception x)
         {  }
    }
}

0 个答案:

没有答案