Static Methods
Static Methods
Static/Class methods
There are two types of methods.
Instance methods are associated with an object and use the instance variables of that object. This is the default.
Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given
a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is
unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to
variables. This is typical of methods which do some kind of generic calculation. good example of this are the many utility methods in the
predefined Math class. !See "ath and java.util.#andom$.
Qualifying a static call
%rom outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance
method, eg, inputTF.setText("");
static method is called by prefixing it with a class name, eg, Math.max(i,j);. &uriously, it can also be 'ualified with an object, which will
be ignored, but the class of the object will be used.
Example
(ere is a typical static method.
class MyUtils {
. . .
//================================================= mean
public static duble mean(int!" p) {
int sum = #; // sum $ all the elements
$% (int i=#; i&p.len'th; i(() {
sum (= p!i";
)
%etu%n ((duble)sum) / p.len'th;
)//endmethd mean
. . .
)
The only data this method uses or changes is from parameters !or local variables of course$.
Why declare a method static
The above mean() method would work just as well if it wasn)t declared static, as long as it was called from within the same class. If called
from outside the class and it wasn)t declared static, it would have to be 'ualified !uselessly$ with an object. *ven when used within the class, there are
good reasons to define a method as static when it could be.
Documentation. nyone seeing that a method is static will know how to call it !see below$. 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. compiler will usually produce slightly more efficient code because no implicit object parameter has to be passed to the method.
Calling static methods
There are two cases.
Called from within the same class
+ust write the static method name. *g,
// *alled $%m inside the MyUtils class
duble a+',tt = mean(attendance);
Called from outside the class
If a method !static or instance$ is called from another class, something must be given before the method name to specify the class where the
method is defined. %or instance methods, this is the object that the method will access. %or static methods, the class name should be
specified. *g,
// *alled $%m utside the MyUtils class.
duble a+',tt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of the object will be used.
Accessing static variables
ltho a static method can)t access instance variables, it can access static variables. common use of static variables is to define
,constants,. *xamples from the +ava library are Math.-. or *l%./01. They are 'ualified with the class name, so you know they are
static. ny method, static or not, can access static variables. Instance variables can be accessed only by instance methods.
Alternate call
-hat)s a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad
because it creates the impression that some instance variables in the object are used, but this isn)t the case.
Reference 2:
Understanding Instance and Class Members
In this section, we discuss the use of the static keyword to create fields and methods
that belong to the class, rather than to an instance of the class.
Class Variables
When a number of objects are created from the same class blueprint, they each have their
own distinct copies of instance variables. In the case of the 2icycle class, the instance
variables are cadence, 'ea%, and speed. Each 2icycle object has its own values for
these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is
accomplished with the static modifier. ields that have the static modifier in their
declaration are called static fields or class variables. They are associated with the class,
rather than with any object. Every instance of the class shares a class variable, which is in
one fi!ed location in memory. "ny object can change the value of a class variable, but
class variables can also be manipulated without creating an instance of the class.
or e!ample, suppose you want to create a number of 2icycle objects and assign each a
serial number, beginning with # for the first object. This I$ number is uni%ue to each
object and is therefore an instance variable. "t the same time, you need a field to keep
track of how many 2icycle objects have been created so that you know what I$ to
assign to the ne!t one. Such a field is not related to any individual object, but to the class
as a whole. or this you need a class variable, numbe%3$2icycles, as follows&
public class 2icycle{
p%i+ate int cadence;
p%i+ate int 'ea%;
p%i+ate int speed;
// add an instance variable for the object ID
p%i+ate int id;
// add a class variable for the number of Bicycle objects
instantiated
p%i+ate static int numbe%3$2icycles = #;
......
)
'lass variables are referenced by the class name itself, as in
2icycle.numbe%3$2icycles
This makes it clear that they are class variables.
Note: (ou can also refer to static fields with an object reference like
my2i4e.numbe%3$2icycles
but this is discouraged because it does not make it clear that they are class variables.
(ou can use the 2icycle constructor to set the id instance variable and increment the
numbe%3$2icycles class variable&
public class 2icycle{
p%i+ate int cadence;
p%i+ate int 'ea%;
p%i+ate int speed;
p%i+ate int id;
p%i+ate static int numbe%3$2icycles = #;
public 2icycle(int sta%t*adence, int sta%t5peed, int sta%t6ea%){
'ea% = sta%t6ea%;
cadence = sta%t*adence;
speed = sta%t5peed;
// increment number of Bicycles and assign ID number
id = ++numberOfBicycles
)
// ne! method to return the ID instance variable
public int 'et.1() {
%etu%n id;
)
.....
)
Class Methods
The )ava programming language supports static methods as well as static variables. Static
methods, which have the static modifier in their declarations, should be invoked with
the class name, without the need for creating an instance of the class, as in
*lass7ame.methd7ame(a%'s)
Note: (ou can also refer to static methods with an object reference like
instance7ame.methd7ame(a%'s)
but this is discouraged because it does not make it clear that they are class methods.
" common use for static methods is to access static fields. or e!ample, we could add a
static method to the 2icycle class to access the numbe%3$2icycles static field&
public static int 'et7umbe%3$2icycles() {
%etu%n numbe%3$2icycles;
)
*ot all combinations of instance and class variables and methods are allowed&
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
'lass methods can access class variables and class methods directly.
'lass methods cannot access instance variables or instance methods directly+
they must use an object reference. "lso, class methods cannot use the this
keyword as there is no instance for this to refer to.
Constants
The static modifier, in combination with the $inal modifier, is also used to define
constants. The $inal modifier indicates that the value of this field cannot change.
or e!ample, the following variable declaration defines a constant named -., whose
value is an appro!imation of pi ,the ratio of the circumference of a circle to its diameter-&
static $inal duble -. = 8.9:9;<=>;8;?<@<8;
'onstants defined in this way cannot be reassigned, and it is a compile.time error if your
program tries to do so. /y convention, the names of constant values are spelled in
uppercase letters. If the name is composed of more than one word, the words are
separated by an underscore ,0-.
Note: If a primitive type or a string is defined as a constant and the value is known at
compile time, the compiler replaces the constant name everywhere in the code with its
value. This is called a compile-time constant. If the value of the constant in the outside
world changes ,for e!ample, if it is legislated that pi actually should be 1.234-, you will
need to recompile any classes that use this constant to get the current value.
The Bicycle Class
"fter all the modifications made in this section, the 2icycle class is now&
public class 2icycle{
p%i+ate int cadence;
p%i+ate int 'ea%;
p%i+ate int speed;
p%i+ate int id;
p%i+ate static int numbe%3$2icycles = #;
public 2icycle(int sta%t*adence, int sta%t5peed, int sta%t6ea%){
'ea% = sta%t6ea%;
cadence = sta%t*adence;
speed = sta%t5peed;
id = ((numbe%3$2icycles;
)
public int 'et.1() {
%etu%n id;
)
public static int 'et7umbe%3$2icycles() {
%etu%n numbe%3$2icycles;
)
public int 'et*adence(){
%etu%n cadence;
)
public +id set*adence(int neABalue){
cadence = neABalue;
)
public int 'et6ea%(){
%etu%n 'ea%;
)
public +id set6ea%(int neABalue){
'ea% = neABalue;
)
public int 'et5peed(){
%etu%n speed;
)
public +id apply2%a4e(int dec%ement){
speed C= dec%ement;
)
public +id speedUp(int inc%ement){
speed (= inc%ement;
)
)