Reputation: 87
I can't figure out why is my class not serializable. As you can see below in my code my class implements Serializable interface.
public class Firm {
PrintWriter out = new PrintWriter(System.out, true);
Scanner sc = new Scanner(System.in);
Set<Worker> workers = new HashSet<>();
boolean saveToFile(){
String fileName = "text.txt";
ObjectOutputStream file;
boolean save = false;
try{
file = new ObjectOutputStream(new FileOutputStream(fileName));
file.writeObject(workers);
file.close();
save = true;
}catch(IOException e){
e.printStackTrace();
}
return save;
}
}
import java.io.Serializable;
public abstract class Worker implements Serializable {//Code
Any ideas how to fix it?
Upvotes: 0
Views: 625
Reputation: 34900
You should be assured that all fields in Worker
class also has type which implements Serializable
interface.
According to your class names and stacktrace fragment from your commentary, it is most probably you have field with type Firm
inside Worker
class which is not serializable due to its structure.
So, you have to do as minimum 2 things:
1) Firm
class also has to implement Serializable
interface
2) mark Scanner
field as transient
Upvotes: 0
Reputation: 198014
The problem is that the PrintWriter
and the Scanner
are not serializable; you can't serialize I/O connections like that.
Move those to wherever you're using them, if you need them at all, as local variables. Don't store them in the class.
Upvotes: 2