Trouble understanding static
Like the topic says, I do use it (actually I have to for the GUIs or they don't compile), but I really don't understand too much about them (what they allow, what they limit) and the definition on java.sun is not very clear to me. Could someone please give me a brief explanation on this subject and maybe an example?
[326 byte] By [
sharokua] at [2007-11-27 4:29:08]

A static method/variable belongs to the class, not a specific instance of the class. http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html> I do use it (actually I have to for the GUIs or they don't compile)You are probably doing something wrong, then.
Static basically means:
* the member ( variable or method ) is associated with the class and not an instance.
* the same member is shared among all the instances, each instance does NOT get it's own copy.
* since the static member exists before an instance is ( or may be )created, there is a restriction that static members can only access other static members ( since the instance members may not even exist when the static code runs! ). They cannot refer to this or super either since those are also related to an instance.
* you do not need to instantiate the object to be able to use the member. You've never created an object of java.lang.Math to be able to use the random() method have you?
public class Test {
private String myName = "My name is . . .!"; //private variable of class Test
public static void main(String[] argv)//is static because the runtime environment needs to call this first, before making any objects, so it's not essential for your class, just gives you a way of running your code from within your class itself
{
String theNameMainGets = ""; //main will receive the name in this
Test testThis = new Test(); //make an instance without a name
Test testThisWithAName = new Test("nogoodatcoding"); //pass a cool name to the constructor :D
//theNameMainGets = whatIsMyName(); //will not work since main is static, so even though it is part of the same class, it cannot call a non-static member, whatIsMyName, because a copy of that is with every instance, and when main calls it, the instance may not exist
theNameMainGets = testThis.whatIsMyName(); //correct way to access the non-static member, by creating an instance and then using that to access it
System.out.println(theNameMainGets);
theNameMainGets = testThisWithAName.whatIsMyName();
System.out.println(theNameMainGets);
//note, you can't say, testThis.myName; since myName is private to testThis.
}
Test()
{
myName = "No one named me";
}
Test( String newName )
{
myName = newName;
}
public String whatIsMyName()
{
return myName;
}
}
Hope this helps