Tuesday, July 28, 2009

How can I call a method from something that retruns a pointer in java?

I have something similar to this


class MyInteger(){


int num;


public void Get(){return num;}


}





class MyChar{


char c;


public void Get(){return c;}


}





and it is stored in a linked-list pointed to by an iterator





so i have a function itr.retrieve() that gives me either a MyInteger or MyChar object, and I need to do this:





(itr.retrieve()).Get()





but that statement gives me an error.


what can I do to get that item instead of the "pointer" to that item?

How can I call a method from something that retruns a pointer in java?
This is kind of a shot in the dark since you didn't list what the error is, and you don't specify what type of linked list you're using (did you make your own, or did you use one from the java api)





The first thing I notice is that your MyInteger class has parens after its declaration and your Get() functions are both declared to return nothing (void). Those are problems.





Another potential problem is that your itr.retrieve() function is probably returning an Object, which the compiler does not think has a Get function. To correct this, you need to make an interface you can cast your Object to, which will then give you access to the Get() function.





interface MyDataType


{


public String Get();


}





class MyInteger implements MyDataType


{


int num;


public String Get()


{


return Integer.toString(num);


}


}


class MyChar implements MyDataType


{


char c;


public String Get()


{


return Character.toString(c);


}


}





you can then get the String value using


((MyDataType)itr.retrieve()).Get();


No comments:

Post a Comment