Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Different object types (references)

KujtimKujtim Posts: 2Member
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.