【发布时间】:2016-10-03 12:04:17
【问题描述】:
我正在阅读有关瞬态和最终关键字的信息,我找到了我们不能将瞬态关键字与最终关键字一起使用的答案。我试过但很困惑,因为它在这里工作正常。
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class SerExample{
public static void main(String... args){
Student foo = new Student(3,2,"ABC");
Student koo = new Student(6,4,"DEF");
try
{
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(foo);
oos.writeObject(koo);
oos.close();
fos.close();
}
catch(Exception e){/**/}
try{
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println(ois.readObject());
System.out.println(ois.readObject());
fis.close();
ois.close();
}catch(Exception e){/**/}
}
}
这是可序列化的学生类代码:
class Student implements Serializable{
private transient final int id;
private transient static int marks;
private String name;
public Student(int id, int marks, String name){
this.id = id;
this.marks = marks;
this.name = name;
}
public Student(){
id=0;
}
@Override
public String toString(){
return (this.name + this.id + this.marks);
}
}
带有transient关键字的代码输出。
ABC04
DEF04
不带瞬态关键字的输出。
ABC34
DEF64
您能解释一下为什么它运行良好吗?有错误吗?
最后,使用 final 关键字的瞬态行为应该是什么?
【问题讨论】:
标签: java serialization java-8 final transient