We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
why static? (Read 364 times)
why static?
Apr 10th, 2006, 1:56am
 
I was trying to find a simple explanation of why I would declare something static or not on the web and I can't find one.

I get the use of final. For eg:
Code:

int choice = 1;
final int myChoice = 1;
switch(choice){
case myChoice:
println("hello");
break;
default:
println("goodbye");
break;
}

Without final I wouldn't be able to give names to the states of my program within the switch() statement. Java wants the switch() to use constants for its cases.

But why am I using static? Am I making things faster by doing thus? Or just typing too much?
Re: why static?
Reply #1 - Apr 10th, 2006, 8:19am
 
1. Static allows you to declare variables that are shared by all instances of a certain class, which can be useful for inter-object communication (just make sure that variables are initialized).

2. You can also use static to declare variables and methods in a class that can be accessed without instantiating the class.

3. Lastly, a static method can only operate on static variables, non-static variables require an actual instance.

I believe static variables also have a speed advantage, since the run-time compiler doesn't have to search for the specific instance.
Re: why static?
Reply #2 - Apr 10th, 2006, 1:48pm
 
the other reason for the confusion is that the "final int" instead of "static final int" syntax was introduced after java 1.1. while the two seem similar, in use they have very little to do with each other. when making a variable that's a field of a class, use static final int, but when you need to make an inline constant inside a method, use "final int". the latter syntax was introduced so that things like inner classes could be created (see the questions elsewhere about using things like invokeLater(), which requires only 'final' objects be used locally).
Page Index Toggle Pages: 1