Help setting a private static class variable
Hi there, I'm working on my assignment for uni and I'm having a few problems with one of the questions.
So I'm trying to set the class variable currentLeader to an object of the LongJumper class, it should be null on first run.
Code :
/*class variables */
private static LongJumper currentLeader;
then after the first jumper goes he should be set as the currentLeader, which I think I have under control but it's all coming unstuck when I try to use the private setter.
Code :
/**
* A private class setter method for the class variable currentLeader
*/
private static void setCurrentLeader()
{
LongJumper.currentLeader = this;
}
My compiler has told me "non-static variable this cannot be referenced from a static context."
I think know how to set it for an int, but setting it for an object has really thrown me :-L
Code :
private static void incremenInt()
{
class.int = class.int + 1;
}
I'd really appreciate if someone would be kind enough to offer me a few pointers on where I'm going wrong this, as I've pretty much run out of ideas and my course work doesn't seem to have included this type of scenario.
Thanks
edit. sorry if this is a little garbled I've been working on this for the past 6 hours :(
Re: Help setting a private static class variable
The keyword 'this' is used to refer to an instantiated object and cannot be used statically. To overcome this you can remove the static keyword from your function
Code :
/**
* A private class setter method for the class variable currentLeader
*/
private void setCurrentLeader()
{
LongJumper.currentLeader = this;
}
You could also do this by creating a static setter with the object to set as the parameter
Re: Help setting a private static class variable
Thanks for replying copeg, unfortunately the question specifically asks for a class method to used for the setter.
Quote:
You could also do this by creating a static setter with the object to set as the parameter
do you mean something along the lines of
Code :
private static void setCurrentLeader(LongJumper aJumper)
and if that's the case, how would I send a message from a LongJumper object with itself as the argument?
eg
Code :
if (LongJumper.getCurrentLeader()== null)
{
setCurrentLeader(this.LongJumper);
}
Re: Help setting a private static class variable
Re: Help setting a private static class variable
thanks mate, I think the problem must be with my class setter method
Code :
private static void setCurrentLeader(LongJumper aJumper)
{
LongJumper.currentLeader = aJumper;
}
My understanding is that when I call the LongJumper referenced by "this" becomes "aJumper" which then becomes currentLeader. Unfortunately it's not working like that, as the currentLeader class variable stays null.