How do I set a static variable??
Hi all.
I'm working on a problem for a school project.
Bascially I have to set a static variable within a class. I have declared the variable as follows:-
Code :
private static Horse theLeadingHorse;
I now have to get and set this static variable by using two class methods. The setter has to be declared as private and the getter as public.
how do I do this??? I have been racking my brains for hours now but no luck!! it's really starting to do my head in.
Basically the getter class method has to return the variable and the setter class method has to set this horse as the leader (ie. the winner).
Anyone any ideas or suggestions?????
Any help would be greatly appreciated.
thanks in advance
John
Re: How do I set a static variable??
implement the setter method non-statically. This way it will set the variable based on the instance information with each appropriate horse object. Then, implement the getter method statically so you can access it without having to go through any horse objects, but rather through the main class itself. To access static methods/fields: it's just like accessing instanced variables/methods except you use the class name.
Code :
public class Horse
{
// static initialization
private static String winner = "none";
public static String getWinner()
{
return winner;
}
}
Code :
public class Main
{
public static void main(String[] args)
{
// obviously, it will say "none" right now, but you can add this somewhere latter in you app and if winner has changed, it will reflect that at call time
Horse.getWinner();
}
}
Re: How do I set a static variable??
Hi,
Thanks for the suggestion but basically in my project I have to do it a certain way.
basically the static variable has to be one of the Horse classes. In other words the variable will hold a class.
Then the getter method will return which class is stored in the variable theLeadingHorse.
(It's hard to explain) :)
The setter method bascially sets the variable (theLeadingHorse) to a class.
I tried doing it as follows:-
Code :
public static Horse getTheLeadingHorse()
{
return Horse.theLeadingHorse
}
private void setCurrentLeader()
{
// no idea how to set theCurrentLeader to hold the name of the leadingclass!!!
}
Am i doing this totally wrong???
Re: How do I set a static variable??
Hmm... If I understand you correctly, theLeadingHorse should hold a Horse object, not a Horse class (kind of a big difference). In this case, you can do what it is I said but with Horse objects rather than String objects. I'm guessing setCurrentLeader is called from the horse object that's currently the leader:
Code :
private void setCurrentLeader()
{
Horse.theLeadingHorse = this;
}
Also, fyi in your code above you're missing a semi-colon in the getTheLeadingHorse() method.
Re: How do I set a static variable??
Thankyou so much!!
This is exactly what I was looking for. All the books etc I have don't show this! I've been having trouble with it for a while. thanks!