Class Variables in Java

In this post, you will learn to:

  • Describe class variables.
  • Declare and access class variables.
  • Class and instance variables.
  • Describe static methods.
  • Advantages and disadvantages of static methods.
  • State the syntax of static initializers.

Class Variables

Class variables are declared using the static keyword. All instances of the class share the same value of the class variable. The value of a class variable can be accessed and modified by using class methods or instance methods. Once the value is modified, all instances of the class are updated to share the same value.

Declare Class Variables

Fields 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 fixed location in memory. Any object can change the value of a class variable,but class variables can also be manipulated without creating an instance of the class.

The following is the syntax to declare class variables.

<static> <data_type> <variable_name>;

where,
<static> implies that all instances of the class share the same static variable
<data_type> is the data type of the variable.
<variable_name> is the name of the variable.

The following code snippet shows the declaration of class variables.

class Book{
   static int price=0;
}

Access Class Variables

Class variables are referenced by the class name itself. This makes it clear that they are class variables. The following is the syntax to access class variables.

<class_name>.<variable_name>

where,
<class_name> is the name of the class where the variable is declared.
<variable_name> is the variable name.

The following code snippet demonstrates how to declare and reference class variables.

class LocalDemo{
    static int price=1;
    public static int getCost() {
        return LocalDemo.price;
    } 
}

Class and Instance Variables

The table below lists the differences between instance and class variables.

Instance variables Class variables
They are initialized only when the class is instantiated. They are static variables and are assigned a default value even before the class is instantiated.
They can be accessed only by using an object reference. They can be accessed by using the object reference as well as the class name. Since, they are called class variables it is advisable not to use object references to access static or class variables.
Each new instance of the class has its own copy of the variable. All instances of the class share the same copy of the static variable.

Static Methods

Static methods, also known as class methods, do not have reference to any instance variable in a class.These are used to access class variables and methods. However, static methods cannot access instance variables or methods directly. The keyword this cannot be used inside a static method.

The following is the syntax for declaring static methods.

<static><return_type><method_name>(<parameter_list>) {
   //body of method
}

where,
<static> is the keyword for declaring a static method.
<return_type> is the data type of the value returned by the method.
<method_name> is the name of the method.
<parameter_list> is the list of parameters.

Static methods can be accessed by using a class name or an instance name. However, accessing static methods using instance is not recommended, as it violates the principle that class methods should be accessible to only classes, not instances.

The following is the syntax to access static methods.

<class name>.<class method>

The following code demonstrates how to declare and access static methods.

class StatMethDemo {

    public static int sum() {
       int sum = 0;
       int pt = 5;
       for (int i=0; i<pt; i++) {
          sum += pt;
       }
 
       System.out.println(“Total Sum is: “ + sum);
       return sum;
    }
 
    public static void main(String args[]) {
       StatMethDemo.sum();
    } 
}

Output:

Total Sum is: 25

Advantages and Disadvantages of Static Methods

The advantages of static methods are as follows:

  1. Static methods can be invoked by using the class name directly.
  2. Static methods can be used to implement behaviors that are not influenced by the state of any instances.
  3. Static methods can be re-defined in instances.
  4. Static methods can be accessed by using the dot operator with an instance of the class. This is however a syntax anomaly since the compiler actually replaces the instance reference with the class name before invoking the method.

The disadvantages of static methods are as follows:

  1. A static method can be called by using an un-initialized object reference. The compiler only checks for the type of the object and whether the method being called is a static method. Hence, a static method can be accessed even by using an un-initialized object reference variable.
  2. A static method cannot be overridden, although it can be hidden.
  3. Non-static attributes of the class cannot be accessed from within a static method.
  4. Other non-static methods of the class or instance cannot be accessed from within a static method.
  5. Since static methods can be invoked without using an instance of the class containing it, the use of this keyword is prohibited.

Static Initializer

A static initializer is a block of code embraced in curly braces { }. It is preceded by the keyword static.It initializes the static variables in a class. The following is the syntax to declare a static initializers block.

static {
   // initialization code
}

The code snippet demonstrates the use of static initializer.

class StatInit{ 
    static int x = 6;
    static int y;
    // Static initializer
    static{
       for(int count = 0; count < 6; count++){ 
          y += x;
       }
    }
 
    public static void main(String args[]) {
       System.out.println(“Value of x is: “ + x);
       System.out.println(“Value of y after 6 counts is: “ + y);
    }
}

Output:

Value of x is: 6
Value of y after 6 counts is: 36
Note: There can be more than one static initialization block in a class. These can be placed anywhere in the class. Java compiler does not allow forward referencing of class variables in static initialization block. In other words, a static initialization block can reference only those class variables that have been declared before it.
Related Post