简体   繁体   中英

Casting an Object to its father class for avoiding its attributes in Java

I have class SuperYo extending class Persona, like this:

public class SuperYo extends Persona {

   private NotSerializableObj obj1
   private NotSerializableObj obj2
   private NotSerializableObj obj3

}

public class Persona {

   private SerializableObj sObj1
   private SerializableObj sObj2
   private SerializableObj sObj3

}

The thing is, that I add to a LinkedList an Instance of Persona from SuperYo:

LinkedList<Persona> list = new LinkedList<Persona>();
list.add((Persona) superYo);

It adds it as a SuperYo Object! With all the NonSerializableObjs on it... and thus, cant be sent from a Socket :(.

So, the question is... is there any way of "downcasting" an object to its father class, so its attributtes are non present?

Thanks!

Casting is a matter of polymorphism. When you cast an object of type1 to type2, the instance won't change, but you just look at the instance from a new perspective!

If you want to send the child class over the network, you can make the SuperYo members as transient, and fill them on instantiation. Or you can add writeObject() and readObject() methods to your child class.

Implement readObject and writeObject in SuperYo as below:

 private void writeObject(ObjectOutputStream outStream) throws IOException {
    //write attributes from PersonYo only
    outStream.defaultWriteObject();
    outStream.writeObject(sObj1);
    outStream.writeObject(sObj2);
    outStream.writeObject(sObj2);
 }

private void readObject(ObjectInputStream inStream) throws IOException,
                                                          ClassNotFoundException {
    //read attributes from PersonYo only
    inStream.defaultReadObject();
    sObj1= (SerializableObj)inStream.readObject();
    sObj2= (SerializableObj)inStream.readObject();
    sObj3= (SerializableObj)inStream.readObject();
}

Once you do this, there will be no need of down-casting. Also you may have better control on other non-serializable attributes in the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM