-1

I am making code to transfer a list of objects to be serialized into a file and back. The issue is when I first serialize the file, the objects are instantiated using the default constructor instead of the second constructor.

In other words, the output comes out with default values:

0 N/A N/A 01-01-1980 [UCLA]
0 N/A N/A 01-01-1980 [UCLA]
0 N/A N/A 01-01-1980 [UCLA]

But it should be:

1234 Robert Smith 07-05-1980 [UCLA]
2345 Donald Trump 07-05-1980 [UCLA]
3456 Barack Obama 07-05-1980 [UCLA]

Here is my main method:

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // ArrayList list

ArrayList<Student> al = new ArrayList<Student>();
    Date d = new Date(80, 5, 7);
    Student s = new Student("Robert", "Smith", 1234, d, "UCLA");
    Student s2 = new Student("Donald", "Trump", 2345, d, "UCLA");
    Student s3 = new Student("Barack", "Obama", 3456, d, "UCLA");
    al.add(s);
    al.add(s2);
    al.add(s3);

    // serialization test
    FileOutputStream fileOut = new FileOutputStream("StudentList.dat");
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(al);
    out.close();
    fileOut.close();

    // deserialization test
    FileInputStream fileIn = new FileInputStream("StudentList.dat");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    ArrayList<Student> a2 = (ArrayList<Student>) in.readObject();
    in.close();
    fileIn.close();

    System.out.println(a2.size());

    for (Student i : a2) {
        System.out.println(i);
    } // for
} // main

Thanks

EDIT: Adding in Student class

package edu.uga.cs1302.gui;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;


@SuppressWarnings({ "serial", "rawtypes", "deprecation", "unchecked" })
public class Student extends Person implements Serializable {

private String collegeName;

/*
 * public Student() { super(); collegeName = null; } // constructor
 **/
public void setC(String c) {
    collegeName = c;
} // set college

public String getC() {
    return collegeName;
} // get college

public Student(String fName, String lName, int n, Date d, String college) {
    super(fName, lName, n, d);
    collegeName = college;
} // second constructor

public String toString() {
    return super.toString() + " [" + collegeName + "]";
} // to string
} // class

1 Answers1

1

What is happening, is that only the fields of the class that implements Serializable are being written and read.

This is why collegeName is being written and read correctly, because it's in your inherited class that implements Serializable. The other fields belong to the base class and wont do so.

Either declare variables you want serialized separately in Student, or make Person implement Serializable as well.