Static

Definition

Static Method

A static method is one that performs an operation for an entire class and not only on a class's individual objects (a method that performs operations on single objects is called an instance method). A static method can not use any of the non-static variables of the class.

Static Variable

A static variable is one that applies to its whole class, unlike a non-static variable of which there is a new instance for each different object of a class.

Code

To write a static method the keyword static must be used in the method header. There is no implied object (this) in the method code.
A static method header might look something like this:

public static int hiMyNameIsSammieMarkowitz(){
 
}

Examples of Static and Non-Static Methods

Static

public static int gcd(int a, int b){
 
    while(b != 0){
       int temp = b;
       b = a % b;
       a = temp;
 
    }
    return a;
}

This method is from our Fraction class. It is static because it performs the same operation (finding the greatest common divisor) for every object (fraction) in the class. Also it makes no mention of the object Fraction which is a good hint that it will be a static method.

Non-Static

public Fraction multiply(Fraction x){
       return new Fraction(numerator * x.numerator, denominator * x.denominator).reduce();
}

This method is also from our Fraction class. It is not static because it uses particular instance of an object to multiply and also creates new intances of an object when the product is formed into a new Fraction. Since the object name appears in the method header it is quite obvious that this will be a non-static method.

Main Method

The main method is static because it is never part of any object.

Static No No's

When writing a static method make sure that you do not call an instance class or a private instance variable in your code - it will cause a syntax error.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License