序列化的基础写法

import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class Main {

    public static void main(String[] args) throws Exception {
        Son son = new Son("xiaoLi", 20);
        FileOutputStream fos = new FileOutputStream("E://Son.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(son);
        oos.close();

        FileInputStream fis = new FileInputStream("E://Son.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Son son_ = (Son)ois.readObject();
        System.out.println(son_.toString());
        ois.close();
    }
}
class Person implements Serializable {
    private String name;
    private int age;

    public Person(){
        System.out.println("haha");
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return this.getClass().getName()+ ": " + name + ", " + age;
    }
}

class Son extends Person {
    public Son(String name, int age) {
        super(name, age);
    }


}

另外子类在继承父类是会默认调用父类没有参数的构造方法,或者利用super直接调用父类的构造方法,如果既没有super,父类也没有无参构造方法,那就会报错

全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务