This site requires JavaScript, please enable it in your browser!
Greenfoot back
Zamoht
Zamoht wrote ...

2012/11/18

Inheriting and statics

Zamoht Zamoht

2012/11/18

#
Okay so I was wondering if lets say I make a class called AdultClass and in that class I make a static integer like "public static int whatEver;". After this i make two subclasses ChildClass1 and ChildClass2, now both classes has inherited the static integer, but if i change that integer in ChildClass1 does this affect ChildClass2 since both classes comes from the AdultClass or are they seperated?
danpost danpost

2012/11/18

#
If you put 'public static int whatEver' in the 'AdultClass' class, then it belongs to the AdultClass class. Any sub-class can refer to it as 'whatEver' and any other actor class or the world class can refer to it as 'AdultClass.whatEver'. To answer your ultimate question, "are they seperated": No. Be aware, however, that static variables retain their values when resetting the scenario. Only re-compiling will cause a reset of the static variables (without programatically doing it).
Zamoht Zamoht

2012/11/19

#
So would I be able to call 'ChildClass1.whatEver = 10', and would this change the value of 'AdultClass.whatEver'? You might have answered this question in your first answer, but I want to be sure I understand it.
danpost danpost

2012/11/19

#
Yes. From your world class (or other actor classes), you can call it 'ChildClass1.whatEver', 'ChildClass2.whatEver', or 'AdultClass.whatEver'; and any change in value is reflected in all classes. So, if you had
// in AdultClass
static int whatEver = 20;
// in WorldClass
ChildClass1.whatEver++;
System.out.println("" + AdultClass.whatEver);
terminal output would be '21'.
Zamoht Zamoht

2012/11/19

#
Okay I get it now thanks.
You need to login to post a reply.