A - an interface.
B,C,D - implement A.

in an other class, say X, i have an array of A, that will hold some B, C, D.

i have a method that get (int i, A a) and put the a in the i place of the array.
->>>> how do i do it? - i need the actual type of a or i simpy do:

array [i] = a;


6 Years
Discussion Span
Last Post by anilopo

If I understand your question right - not sure I do - the simple assignment should work.
What you should bear in mind is that when you retrieve an A from that array, you won't be able to use any but A methods unless you then cast it back to its original type, if I recall correctly. I think this is correct, but there's a doubt in the back of my mind, so maybe you should verify this, but I think it's correct.

So if A is an interface with methods int foo(int) and void bar(int) , and B has those, but it also has int frotz(int) then the following code will not work:

B b = new b();
array[i] = b;

A a = array[i];
int i = a.frotz(1);   // fail! a doesn't have frotz, even though a is actually a b!

You'd have to cast it back:

A a = array[i];
if (a instanceof B) B b2 = (B) a;
int i = b2.frotz(1);

thx very much!

you answerd me also another question i had :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.