序列化的基础写法
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,父类也没有无参构造方法,那就会报错


查看5道真题和解析