Yoda
Yoda

Reputation: 18068

Serialization of polymorphic objects

I have classes Osoba(Person) and Zawodnik(Constestant)

Contestant extends Person and Person implements Serializable. Does Constestant automatically implements Serializable too? I think so.

The extension (ArrayList ekstensja) of class Person contains objects of different classes extending class Person. Will the method zapiszEkstensje() in the Person class work correctly? I think so.

Example:

public abstract class Osoba implements Serializable {
/....something..../

    private static ArrayList<Osoba> ekstensja = new ArrayList<Osoba>();

    private void dodajZawodnik(Osoba osoba) {
        ekstensja.add(osoba);
    }

    private void usunZawodnik(Osoba osoba) {
        ekstensja.remove(osoba);
    }

    public static void pokazEkstensje() {
        for (Osoba zawodnik : ekstensja)
            System.out.println(zawodnik + "\n");

    }

    public static void zapiszEkstensje() {
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("osoba.ser"));                                                
            outputStream.writeObject(ekstensja); 
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public static void wczytajEkstensje(){
        try {
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("osoba.ser"));                                                
            ekstensja = (ArrayList<Osoba>) (inputStream.readObject()); 
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
}

public class Zawodnik extends Osoba  {  }
// DO I NEED TO MAKE THIS CLASS IMPLEMENT SERIALIZABLE TOO?

Upvotes: 1

Views: 1496

Answers (1)

dcernahoschi
dcernahoschi

Reputation: 15250

According to java doc of Serializable interface, all the subtypes of a serializable class are themselves serializable.

So, the answer is yes, if Person implements Serializable all its children will be serializable.

Upvotes: 1

Related Questions