next up previous
Next: About this document ... Up: The Frightened Freshers Guide Previous: Public and Private

More Keywords

There are some more very important keywords that you need to know about in java.

The static keyword can be used to share a variable between all objects of the same class. This can be useful to have a field like numberOfObjectsCreated and then in the constructor for the Class increment this by one. It is easy to see that without the static keyword the value would always be one. (And if its not, Mr. Capcarre's slides are very good!).

Static variables save on memory space because there is not a new variable having to be stored every time a new object is created from the class. The static keyword allows information to be shared between objects and is useful to represent information which is the same for all objects of the same Class.


\begin{lstlisting}
private static int numberOfObjects;
\end{lstlisting}

The final keyword is used to define constants. So if you wanted a numerical value for pi but did not want to use the inbuilt pi thing in java for some reason you could define pi:
\begin{lstlisting}
private final double mmmPi = 3.14;
\end{lstlisting}

The final keyword means that the value will never be changed (If you try to change it in code then the java compiler will just eat your brains. It is a bug that never got ironed out.)

It may also be useful to have the constant the same for all objects of the same class. keywords can be combined and you can have static final variables (Constants that are the same for all objects in a class)
\begin{lstlisting}
private static final double mmmPi = 3.14;
\end{lstlisting}


next up previous
Next: About this document ... Up: The Frightened Freshers Guide Previous: Public and Private
Tom Carlson 2006-01-10