Different object types (references)

Hello,

I heave an array of objects which each object has some common parameters, but also is to be characterized by adequate specific object. For each object I use 'objectType' parammeter to differentiate, then the rest, I tried as follows (using 'Object' type) but it is not working. Here is the complete simplified code:

class DiffObjectClasses{
public static void main(String [] args)
{
SerialObject so;
IPObject iob;

ObjectType ot[] = new ObjectType[3];

ot[0].objectID=1;
ot[0].objectType=1;
so=new SerialObject();
so.serialPortNo=21;
ot[0].objectContent=so;

ot[1].objectID=2;
ot[1].objectType=1;
so=new SerialObject();
so.serialPortNo=21;
ot[1].objectContent=so;

ot[2].objectID=3;
ot[2].objectType=2;
iob=new IPObject();
iob.host="localhost";
iob.port=2200;
ot[2].objectContent=iob;

System.out.println("----------------------------");
for(int indx=0; indx<ot.length;indx++)
{
System.out.println("ObjID:"+ot[indx].objectID);
System.out.println("ObjType:"+ot[indx].objectType);
switch(ot[indx].objectType)
{
case 1:
so=(SerialObject)ot[indx].objectContent;
System.out.println("Serial port no:"+so.serialPortNo);
break;
case 2:
iob=(IPObject)ot[indx].objectContent;
System.out.println("IP host:"+iob.host);
System.out.println("IP port:"+iob.port);
break;
}
}
}
}

class ObjectType{
int objectID;
int objectType;
Object objectContent;
}

class SerialObject{
int serialPortNo;
}

class IPObject{
String host="";
int port;
}

I've worked in C/C++, it was very simple by declaring 'void' member and then using implicit conversion as here but it sin't working in Java.

Kujtim
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories