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

2016/11/15

Setting a variable in a superclass from the subclass

Baguette Baguette

2016/11/15

#
In the game I'm creating, I have all my actors as subclasses of a "Mover class", so I can set a variable (such as int scrollSpeed) that can be accessed by all the subclasses (like move(scrollSpeed);) but be modified within a subclass (like dX=scrollSpeed+runSpeed;). I have a button object class called "Play" and when it gets clicked it drops out and gets removed from the world. Before the "Play" object gets removed I want it to set the scrollSpeed variable in the superclass "Mover" =-4 so Objects of class Mover start moving left. What is the best way to set the variable scrollSpeed from the subclass?
Super_Hippo Super_Hippo

2016/11/15

#
Make 'scrollSpeed' static, then you can use
1
Mover.scrollSpeed = -4;
Baguette Baguette

2016/11/16

#
Works brilliantly Hippo. Thank you. If you have a chance could you explain what making a variable static does?
Super_Hippo Super_Hippo

2016/11/16

#
Static variables do not belong to an object, they belong to a class. So every object from the class is using the same variable. A special thing is that a line like this...
1
protected static int scrollSpeed = 4;
...is only executed when the scenario is compiled, not when you reset it. So you may need a 'Mover.scrollSpeed=4;' line in the constructor of your first world.
Baguette Baguette

2016/11/16

#
Ah! The static variable makes sense now. Thank you. That will help me in the future as well. It works without me making the variable protected... so making a variable protected means it stays the same through a reset or new construction of an object?
Super_Hippo Super_Hippo

2016/11/16

#
No, protected only means that it is accessible by the class and all its subclasses. Private is for only the class itself and public is for all classes. So the last advice I made is actually only possible if it is public. I messed this up it seems.
You need to login to post a reply.