View Single Post
  #3   Spotlight this post!  
Unread 13-01-2011, 12:40
correnos correnos is offline
Registered User
FRC #2342
 
Join Date: Jan 2010
Location: Nashua, NH
Posts: 6
correnos is an unknown quantity at this point
Re: Working with java classes

Quote:
Originally Posted by eagle33199 View Post
Your problem here is thinking of them as classes with methods instead of objects.

For most work in Java, you'll create objects from your classes. For example:
RobotCode myCode = new RobotCode();

Then you do operations on that object, myCode. You'll access your functions with something like:
myCode.isEnabled();

This gives you flexibility in creating multiple objects - for example, you'll probably want to create a new object for each of the Jaguars you have. When you create it, you tell it where the Jaguar is hooked up, and don't have to worry about specifying that location ever again.

Outside of all this, Java recognizes that sometimes you don't really need/want to specify a new object when accessing a class, class methods, or class variables. For this, they have the static context. If you declare it static, it can be accessed straight from the class itself. This is called a singleton, as there's only a single instance of it you can use, and everyone who calls it gets the same instance of that class. You need to be very careful with this, as any class variables that are modified in one location, will read that modified value in another, sometimes with horrible results!

So to access your isEnabled() class in a static way, you need to declare it as follows:

public static Boolean isEnabled()
{
...
}

I'm assuming here that the return type is Boolean, and that you want it to be publicly available (as opposed to private or protected).

Likely you'll want to go with the first method, and not do too much static code... at least, not until you really understand the difference and the impact!
With most Java programs, creating an object from a class is the advisable path. However, I am unaware of how to accomplish this from the setup used by wpilibj. It is configured on the JVM of the cRIO to run the main class, and if there is a way to tell it to work with an instance of said class instead of the class itself I have not found it yet.