We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I try to write generic method to pass different class by this one. My idea is test the obect to see if it is an instance of my target class, but when I'm testing positively the nature of class, I cannot catch the method or var of this class :
Mother mother = new Mother(1) ;
ArrayList<Mother> list_mother = new ArrayList<Mother>() ;
void setup() {
list_mother.add(mother) ;
method_list(list_mother) ;
}
void method_list(ArrayList list) {
for(Object obj : list) {
if(obj instanceof Mother) {
println("list Mother") ;
println(obj.x) ;
}
}
}
class Mother {
int x ;
Mother(int x) {
this.x = x ;
}
}
Answers
In line 11
obj
is declared as anObject
this class does not have an attribute calledx
so when you come to use it in line 14 it doesn't work. The trick is to cast the variableobf
toMother
CHange line 14 to
println( ((Mother)obj).x ) ;
Or even better do this
Whaouuu, it's so simple...Sure alone I take one week to find it :) thx a lot for the trick.
A more refined example: :bz
Generally it is considered bad practice to use the
instanceof
operator. Using an interface is one way to avoid its use.That's sound very good to can use the interface name to create a list. Big step for me. But if I create few extends class of Mother? I must still use instanceof
Interface Agent is both a marker/label & a contractor.
That is, any class which
implements
it orextends
some class that does it already, is guaranteed to have the method get_x() therein.However, your subclass Child got an exclusive method called get_y(), which is outside Agent's contract.
Therefore, in order to invoke get_y(), you're gonna need to cast it as
(Child)
. #-o@gotoloop I ask a question about
instanceof
because @quark say is not a good practice. there is an other way to castAgent
toChild
whitoutinstanceof
?Classic inheritance, which is based on
extends
keyword, is far from perfect. =((There are other approaches like composite inheritance and trait build classes, etc.
Quickest dirty fix is to add get_y() to interface Agent.
But as you may be guessing by now, that'd oblige class Mother to implement that as well, even though it doesn't need that method, forcing all classes implementing interface Agent to increase their "baggage" weight unnecessarily. :-@
Thx a lot for all precious informations about interface, instanceof, implements...