Static Fields in Java with Example
In each object of a class will have its own copy of all the fields of the class. However, in certain situations, it may be required to share a common copy of fields among all the objects of the same class. This is accomplished by declaring the field(s) to be static and such fields are known as static field(s). If a field is declared static then there is one field for the entire class instead of one per object. A static field of a class is often referred to as a class variable because static field is associated with a class and not with individual instances of the class. A static field gets memory only once for the whole class no matter how many objects of a class are created. To declare a static field, prefix the field declaration in the class with the static modifier. Its syntax is,
static datatype fieldName;
class Rectangle
int length; //length of rectangle
int breadth; //breadth of rectangle
static int rectCount =0; //count rectang objects
void setData(int l,int b)
length=l;
breadth=b;
rectCount++;
>
//method to calculate area of rectangle
int area()
int rectArea;
rectArea = length * breadth;
return rectArea;
>
>
//class to create Rectangle objects and access static field
class StaticField
public static void main(String[] args)
//create first rectangle object
Rectangle firstRect =new Rectangle();
firstRect.setData(5,6);
System.out.println("Area of Rectangle 1 : "+firstRect.area());
//create second rectangle object
Rectangle secondRect =new Rectangle();
secondRect.setData(10,20);
System.out.println("Area of Rectangle 2 : "+secondRect.area());
// access static field of rectangle class
System.out.println("Total Number of Objects : "+ Rectangle.rectCount);
>
>
In the above example, the class Rectangle has two instance variables length and breadth and one class variable rectCount. When we create firstRect and secondRect objects of type Rectangle, each has its own copy of length and breadth instance variables but both share a single copy of class variable rectCount. The class variable rectCount is initialized to 0 only when the class is first loaded, not each time a new object is made. When the object firstRect is created and the setData () method is invoked, the static variable rectCount is incremented by 1 and it is set to 1 (= 0+ l). Similarly, when the object secondRect is created and the setData () method in invoked the value of rectCount variable is set to 2 (= 1+l). Finally, the statement,
System.out.println(“Total Number of Objects : “+ Rectangle.rectCount);
prints the total number of objects.
From the above example, we find that one use of class variable is to keep a count of how many objects of a class have been created in your program another use of class variable is to define constants which are shared by all the objects of the class. To understand this, let us consider a problem which maintains account information of multiple customers by updating the balance periodically with the same interest. In order to simulate it, we create a Account class which contains the fields like account number, balance, rate of interest etc. To represent individual customer, we need to create an object. Each object will store all its fields in separate memory location. As we have different account number and balance for every Account object but the rate of interest for all the account object is the same. So allocation of separate memory to data member rate of interest for all the objects will cause the following problems.
a) Wastage of memory space will occur because the same value of rate of interest is maintained by all the objects of Account class.
b) If the value of rate of interest changes over time, then each copy would have to be updated that can lead to inefficiency, wastage of time and greater potential of errors.
So in order to overcome this problem, we need to store the rate of interest only once in memory which can be shared by all the objects of the same class. This problem can be solved by declaring the ‘rate of interest’ as a static field. But this may lead to accidental modification as it may be accessed from outside the class and lead to undesirable effects on the efficiency and reliability of the program. In such a case, you have to use the final keyword along with static so that this field can never have its value changed.
Properties of Static Field
A static field of a class has the following characteristics:
1. There is only one copy of static field in a class which is shared among all the objects of the class.
2. A static field can be accessed before any object of a class is created, without reference to any object.
3. To make a static field constant in Java, make a variable as both static and final.
4. The static field is similar to static variable. The main difference is that a static variable is used to retain information between calls whereas static field is used to share information among multiple objects of a class.
You’ll also like:
Understanding 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 Bicycle class, the instance variables are cadence , gear , and speed . Each Bicycle 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. 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.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles , as follows:
Class variables are referenced by the class name itself, as in
This makes it clear that they are class variables.
You can use the Bicycle constructor to set the id instance variable and increment the numberOfBicycles class variable:
public class Bicycle < private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear)< gear = startGear; cadence = startCadence; speed = startSpeed; // increment number of Bicycles // and assign ID number id = ++numberOfBicycles; > // new method to return the ID instance variable public int getID() < return id; >. >
Class Methods
The Java 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
instanceName.methodName(args)
A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:
public static int getNumberOfBicycles()
Not 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.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directlythey must use an object reference. Also, 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 final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI , whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By 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 (_).
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 example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
The Bicycle Class
After all the modifications made in this section, the Bicycle class is now:
public class Bicycle < private int cadence; private int gear; private int speed; private int id; private static int numberOfBicycles = 0; public Bicycle(int startCadence, int startSpeed, int startGear) < gear = startGear; cadence = startCadence; speed = startSpeed; >public int getID() < return id; >public static int getNumberOfBicycles() < return numberOfBicycles; >public int getCadence() < return cadence; >public void setCadence(int newValue) < cadence = newValue; >public int getGear() < return gear; >public void setGear(int newValue) < gear = newValue; >public int getSpeed() < return speed; >public void applyBrake(int decrement) < speed -= decrement; >public void speedUp(int increment) < speed += increment; >>