Java Prac2
Java Prac2
There will be times when you will want to define a class member that will be used independently
of any object of that class. Normally a class member must be accessed only in conjunction with
an object of its class. However, it is possible to create a member that can be used by itself,
without reference to a specific instance.
To create such a member, precede its declaration with the keyword static. When a member is
declared static, it can be accessed before any objects of its class are created, and without
reference to any object.
The most common example of a static member is main( ). main( ) is declared as static because
it must be called before any objects exist. Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
There are good reasons to define a method as static
● Documentation.
Anyone seeing that a method is static will know how to call it . Similarly, any programmer
looking at the code will know that a static method can't interact with instance variables,
which makes reading and debugging easier.
● Efficiency.
A compiler will usually produce slightly more efficient code because no implicit object
parameter has to be passed to the method.
Example:
class MyUtils {
. . .
//================================================= mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
. . .
}
From inside the class we can call a static method by just writing the static method name. Eg,
Outside of the class in which they are defined, static methods can be used independently of any
object. To do so, you need only specify the name of their class followed by the dot operator. For
example, if you wish to call a static method from outside its class, you can do so using the
following general form:
classname.method( )
Here, classname is the name of the class in which the static method is declared. As you can
see, this format is similar to that used to call non-static methods through object- reference
variables. This is how Java implements a controlled version of global.
Here is an example.
If an object is specified before it, the object value will be ignored and the the class of the object
will be used.