We are about to switch to a new forum software. Until then we have removed the registration on this forum.
So I thought the code below would work, but it does not...
I'd like to hold some classes that implements an Interface in the same collection, but if I can't access member fields, then maybe it's useless... What am I doing wrong?
I i ;
void setup() {
i = new C();
// throws a cannot be resolved or is not a field
println(i.x);
}
interface I {
}
class C implements I {
int x;
C() {
x= 0;
}
}
Answers
Humm using getters it works... Is this the way to go? Does my interface needs to have all getters?
Jub. Iterfaces only allow you to define functions and constant variables, so if you don't want to use inheritance, setters and getters are the way to go.
Well, if you need to access all variables via your interface, you kinda have to. Or you could spread the setters/getters over multiple interfaces:
i.x
fails b/c field i was declared as of datatype I.println( ((C) i).x );
C c = (C) i;
println(c.x);
Great guys. Thanks a lot.
@GoToLoop why is the extra parenthesis needed in line
I mean this would be enough to cast
right?
The extra parens are needed b/c the operator dot
.
has a higher priority than the(cast)
! @-)@_vk: Because without the parenthesis (
(C)i.x
) the compiler would try to castx
toC
.That is, w/o the extra parens, the
(C)
cast would act upon member x instead of i! >-)Got it. Thanks!!