Java Static Modifier

Objectives

        

Introduction

        

Commentary

        

Interactive Exercises


Commentary
 

Topics

1. Instance Variables and Static (Class) Variables

2. Instance Methods and Static (Class) Methods

3. Simple Code Scenarios

1. Instance Variables and Static (Class) Variables
 

This section describes in more detail instance and static variables.

1.1. Instance Variables
 

Definition: Unless declared as static, a variable is by default referred to as an instance variable. Whenever a new instance (object) of a class is created, a new variable associated with that instance (object) is created for every instance variable declared in that class.

·         An instance variable is always used with respect to an object. From outside the defining class, a public instance variable is used by prefixing it with an object (using the dot notation.)  For example, if Student is a class providing a public instance variable name, this variable is used as follows:

Student student1 = new Student("John Smith");

String name = student1.name;

1.2. Static (Class) Variables

 

Definition: A variable that is declared using the static modifier is called a static variable or a class variable and does not require association with a particular instance (object) of its class. A static variable is incarnated only once when the class is initialized. So, there exists exactly one incarnation of the variable, no matter how many objects (possibly zero) of the class may eventually be created.

·         If only one copy of a particular variable should be shared by all object of a class, a static variable must be used.
 

·         A static variable represents classwide information -- all objects of the class share the same piece of data. 
 

·         It is preferable for static variables to be initialized using a static initializer:
 

static {

//static variables initialization

}

For example, a static variable lastAssignedId could be initialized in the Student class initializer as follows:

public class Student {

...

private static int lastAssignedId;

...

static {

lastAssignedId = 100;

}

...

}
 

·         A static variable is always used with respect to the class in which it is defined. From outside the defining class, a static variable is used by prefixing it with its class name (instead of the name of an object) using the dot notation. For example, if lastAssignedId is a public static variable defined in class Student, it should be invoked as follows:

String StudentID = Student.lastAssignedId;.

It is recommended you always use the class name when referring to static methods and variables even though a static variable can also be invoked using an object of its class.

 

1.3. Using Static and Non-Static Variables

 

In general, you should use static variables when the value(s) of the variable will be shared (and potentially modified) by any other instance of the class. Present in the Java classes that ship with the compiler are many excellent examples of Static variables. For example, the Java Color class uses static variables to define most of the colors with a descriptive string such as Color.RED, Color.BLUE and others. These are then used by programmers to develop interesting graphic objects of differing colors.

 

The following example uses a static variable, count, to keep count of the number of circles instantiated.

 

Example 1: A static variable count that holds the number of created instances of its class.

//defining, initializing, and using the static variable count

class Circle {

double radius;

public static int count = 0;

public Circle (double r) {

radius = r;

count++; //count is incremented each time a Circle object is created

}

}

 

//testing the static variable

public class TestStaticVar {

public static void main (String args[]) {

//create 3 Circle objects

Circle circle1 = new Circle(3.5);

Circle circle2 = new Circle(5.7);

Circle circle3 = new Circle(4.0);

//print the value of the static variable – invoked using the class name

System.out.println("Number of objects = " + Circle.count);

}

 

After you analyze and run the above code, can you should be able to understand the difference between the static variable count and the instance variable radius.

2. Instance Methods and Static (Class) Methods
 

This section describes in more detail instance and static methods.

2.1. Instance Methods

 

Definition: Unless declared as static, a method is by default referred to as an instance or a non-static method.  
 

·         Instance methods are associated with an object and use the instance variables of that object.
 

·         From outside the defining class, an instance method is invoked (called) by prefixing it with an object (using the dot notation,) which is then passed as an implicit parameter to the instance method.

 

For example, if getName() is a public instance method defined in class Student, it should be invoked as follows:

Student student1 = new Student("John Smith");

String name = student1.getName();

2.2. Static (Class) Methods

 

Definition: A method that is declared using the static modifier is called a static method or a class method. A static method is a service provided by a class and does not require association with a particular class instance (object).
 

·         A static method is always invoked (called) with respect to the class in which it is defined. From outside the defining class, a static method is invoked by prefixing it with its class name (instead of the name of an object) using the dot notation. For example:

int maxNum = Math.max(i,j);

Similar to a static variable, a static method can also be invoked using an object of its class, which actually will be ignored and the class of the object will be used. For example:

Math mathObject = new Math();

int maxNum = mathObject.max(i,j);

However, as before, the invocation of  a static method using an object of its class is not recommended, because this creates the impression some instance variables in the object are used, while this is not the case

 

2.3. You can’t reference a non-static variable from main

 

The main() method must be static, because when the application starts there are no objects instantiated. So, the main() method is a service provided by the class and do not require association with a particular class object.

 

 Any method, static or not, can access static variables. Instance variables can be accessed only by instance methods. This may seem uninteresting at first. However, it becomes quite important when designing your Java applications. The following code will not compile until you declare the variable x as static.

public class NonStaticCallError {

    int x;

    public static void main (String args[]) {

       // Will not compile unless x is declared as static

       x = 4;

    } 

}

One simple way to correct the above code is to declare x as static:

public class NonStaticCallError {

    static int x;

    public static void main (String args[]) {

       // Will not compile unless x is declared as static

       x = 4;

    } 

}

2.4. Using Static and Non-Static Methods

 

In general, you should use static methods when the service provided is independent of any other instance of the class. Static methods are commonly used to implement utility type functions and often when the method does not depend on any instance variables. For example, a simple utility to determine the range given any two input numbers could be a good candidate for a static method.

  

The following example uses a static static method called average() to compute the average of the students grades.  

 

Example 2: A static method that calculates the average of the elements of a passed as an argument integer array (note that the only data the average method uses or modifies is from parameters or local variables.)

//defining the static method average

public class Utils {

public static double average (int[] arr) {

int sum = 0;

for (int i=0; i<arr.length; i++) {

sum += arr[i];

}

return sum/arr.length;

}

}

//usaing the average() static method

public class Student {

private String firstName;

private String lastName;

private int [] grades;

public Student(String fn, String ln, int[] gr) {

firstName = fn;

lastName = ln;

grades = gr;

}

public String getFirstName() {

return firstName;

}

 public String getLastName() {

return lastName;

}

public double getAvgScore() {

return Utils.average(grades); //the static method average is prefixed by its class name

}

public printResults() {

System.out.println(getFirstName()+" "+ getLastName()+": "+s1.getAvgScore());

}

}

//testing the class Student and through it the static method average

public class TestStudent {

   public static void main(String args[]) {

      Student s1 = new Student("Ivan", "Brown", new int[] {80,75,92,87});

      Student s2 = new Student("Diana", "Smith", new int[] {83,78,72,90});

      s1.printResults();

      s2.printResults();

   }

}

 

Note: The above average() method would work just as well if it was not declared static, as long as it was invoked from within the same class. If invoked from outside the class and it was not declared static, it would have to be qualified (uselessly) with an object. However, even when used within the same class, there are the following good reasons the method to be defined as static:

  • Documentation -- the fact a method is declared static shows it must be  invoked using the class name, as well as shows it can not interact with instance variables, which makes code reading and debugging easier.
     

  • Efficiency -- the compiler usually produces slightly more efficient code, because no implicit object parameter has to be passed to the method.

3. Simple Code Scenarios

 

public class ExampleClass {

public int var1;                    // instance variable

public static int var2;             // class variable

public void method1() {}            // instance method

public static void method2() {}     // class method

}

 

// application class

public class ExampleApp {

// program entry point

public static void main(String args[]) {

      //…

}

}

Scenario 1

Review the following code:

public class ExampleClass {

public int var1;

public static int var2;

public void method1() { }

public static void method2() { }

}

public class ExampleApp {

public static void main(String args[]) {

ExampleClass.method2();

}

}

Is the following statement correct?

ExampleClass.method2();

Observations:

  • ExampleClass is declared as a class

  • method2() declaration in ExampleClass class contains the static modifier, therefore it is a class method

  • method2() is invoked using the class name

Yes, the statement is correct, because method2()is a class method  and is invoked using the class name.

Scenario 2

Review the following code:

public class ExampleClass {

public int var1;

public static int var2;

public void method1() { }

public static void method2() { }

}

public class ExampleApp {

public static void main(String args[]) {

System.out.println(ExampleClass.var2);

}

}

Is the following statement correct?

System.out.println(ExampleClass.var2);

Observations:

  • ExmapleClass is declared as a class

  • var2 declaration in ExampleClass class contains the static modifier, therefore it is a class variable

  • var2 is invoked using the class name

  • Yes, the statement is correct, because var2 is a class variable and is invoked using the class name.

    Scenario 3

    Review the following code:

    public class ExampleClass {

    public int var1;

    public static int var2;

    public void method1() {}

    public static void method2() {}

    }

    public class ExampleApp {

    public static void main(String args[]){

    ExampleClass myObject = new ExampleClass();

    ExampleClass.method1();

    }

    }

    Is the following statement correct?

    ExampleClass.method1();

    Observations:

    • ExampleClass is declared as a class

    • method1() declaration in ExampleClass class does not contain the static modifier, therefore it is an instance method

    • method1() is invoked using the class name

    No, the statement is not correct -- a compiler error will be generated:

    Non-static method method1 cannot be referenced from a static Context

    The following statement is correct (method1() is invoked using an instance (object) of ExampleClass):

    myObject.method1();

    Scenario 4

    Review the following code:

    public class ExampleClass {

    public int var1;

    public static int var2;

    public void method1() { }

    public static void method2() { }

    }

    public class ExampleApp {

    public static void main(String args[]) {

    ExampleClass myObject = new ExampleClass();

    System.out.println(ExampleClass.var1);

    }

    }

    Is the following statement correct?

    System.out.println(ExampleClass.var1);

    Observations:

  • ExampleClass is declared as a class

  • var1 declaration in ExampleClass class does not contain the static modifier, therefore it is an instance variable

  • var1 is invoked using the class name

  • No, the statement is not correct -- a compiler error will be generated:

    Non-static variable var1 cannot be referenced from a static Context

    The following statement is correct (var1 is invoked using an instance (object) of ExampleClass):

    System.out.println(myObject.var1);

    Scenario 5

    Review the following code:

    public class ExampleClass {

    public int var1;

    public static int var2;

    public void method1() { }

    public static void method2() { }

    }

    public class ExampleApp {

    public static void main(String args[]){

    ExampleClass myObject = new ExampleClass();

    myObject.var2;

    }

    }

    Is the following statement correct?

    myObject.var2;

    Observations:

    • ExampleClass is declared as a class

    • var2 declaration in ExampleClass class contains the static modifier, therefore it is a class variable

    • var2 is is declared as public

    • myObject is an instance of ExampleClass

    • var2 is invoked using an object of ExampleClass

    Yes, the statement is correct, because var2 is a class variable and is invoked using an instance (object) of  its class (which actually will be ignored and the class of the object will be used).

    Scenario 6

    Review the following code:

    public class ExampleClass {

    public int var1;

    public static int var2;

    public void method1() { }

    public static void method2() { }

    }

    public class ExampleApp {

    public static void main(String args[]){

    ExampleClass myObject = new ExampleClass();

    myObject.method1();

    }

    }

    Is the following statement correct?

    myObject.method1();

    Observations:

  • ExampleClass is declared as a class

  • method1() declaration in ExampleClass class does not contain the static modifier, therefore it is an instance method

  • myObject is an instance of ExampleClass

  • method1() is invoked using an object of ExampleClass

  • Yes, the statement is correct because method1() is an instance method and is invoked using an instance (object) of its class.


    ©2006 University of Maryland University College

    home

    .