Abstract class and Serialization

Hi,

I have an abstarct class that has 2 protected String members (name and Xid) , and implemets serializable

I then have a class that extends the abstract.

This new class references

this.name = "somethins" and

this.Xid = "zxxx"

When I try and pass this object over rmi, I get a strange ClassCastException where it says that trying to assign a String to <classname>#Xid

When I changed this.Xid to super.Xid, the problem

disappeared !!!.

Also, the problem appeared only sometimes. If I changes the rmi registry port, the problem seemed to go away.

Its strange. Any comments ?

Thanks

Shahed

[688 byte] By [shahed] at [2007-9-26 9:07:54]
# 1

This is because your derived class does not implement the interface java.io.Serializable.

As you mentioned the problem disappears once as you changed it to reference super class variable.

For successful Serialization, all the members in the hierarchy needs to be Serializable.

AshwinP at 2007-7-1 20:15:02 > top of Java-index,Core,Core APIs...
# 2

Derived classes implement all interfaces implemented by their ancestors.

So

class A implements X { }

class B extends A { }

public class TestThem {

public static void main(String[] args) {

X x = new B();

}

}

is valid... The same should apply for serialisation should it not.

talden at 2007-7-1 20:15:02 > top of Java-index,Core,Core APIs...
# 3

> Derived classes implement all interfaces implemented

> by their ancestors.

>

> So

>

> > class A implements X { }

> class B extends A { }

>

> public class TestThem {

> public static void main(String[] args) {

> X x = new B();

> }

> }

>

>

> is valid... The same should apply for serialisation

> should it not.

Yes, that's right. If a superclass is serializable then the subclass is serializable. You'll know if something is NOT serializable, because it will throw a NotSerializableException when ObjectOutputStream attempts to serialize a non-serializable object.

As for the ClassCastException - where is it thrown? Surely not in the serialization/deserialization part! You can check that by implementing a pair of methods:

private void writeObject(java.io.ObjectOutputStream out) throws IOException {

try {

out.defaultWriteObject();

}

catch (Exception e) {

e.printStackTrace();

}

}

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {

try {

in.defaultReadObject();

}

catch (Exception e) {

e.printStackTrace();

}

}

See the javadocs for java.io.Serializable to see about the two method names.

Hope that helps.

Cameron.

sneezy at 2007-7-1 20:15:02 > top of Java-index,Core,Core APIs...