Skip to main content
gamedev.net
🔒 Locked

[java] Super class casting

Started by helldoggie666 May 17, 2010 at 11:46 AM 1 replies 1k views
Original Post
helldoggie666
helldoggie666
Hi, I have a small problem with the serialization of my objects. I have a basicobject that contains some parameters like a name, position etc. All my objects in my project are extending from this one. Now for sending information over the network, I would like to send only the basicobject part and not the complete extended class.

public class BasicObject {
   String title;
   int posx;
   int posy;
}


public class ExtendedObject extends basicObject {
   Image image;
   Arraylist values;

   public ExtendedObject(Image image){
     this.image = image;
   }
}
I convert my objects to a bytearray and then send them over the network by using sockets. When i cast it back to an object it's from the type ExtendedObject and not BasicObject. Can I do something like

ExtendedObject obj = new ExtendedObject(image1); -> this i have to start with

BasicObject obj = (BasicObject)obj; -> this is what i would like to have, but it doesn't work, I always get an error that the class is not found, which is normal cause the other program doesn't know the class ExtendedObject.

Is it possible to get only the BasicObject information? Thanks! Kind regards
helldoggie666
helldoggie666
Since there are no reactions to my question I believe this is a bit hard to do :-). I solved my problem by creating a new instance of the basicobject with the needed values and use this one instead of the extendedobject. Not the way I wanted it to be. But it will do.

Grtz
Glass_Knife
Glass_Knife
First, you tend to get more people looking at the code examples you post if you put the code in the source tags. See the FAQ for information.

Second, I don't see why the code doesn't work.

  public class A { }  public class B extends A { }	  public void test() {    B b = new B();    A a = b;  }


This works because B "is a" A. You have the same thing going on with your code.

I do see a typo in the code you posted.

public class ExtendedObject extends basicObject {

should be

public class ExtendedObject extends BasicObject {

Maybe that is why it wasn't working?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.