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;

???

Recommended Answers

All 2 Replies

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.