Static Fields and Methods - Core Java

In all sample programs that you have seen, the main method is tagged with the staticmodifier. We are now ready to discuss the meaning of this modifier.

Static Fields

If you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields. For example, let’s suppose we want to assign a unique identification number to each employee. We add an instance field id anda static field nextId to the Employee class:

Every employee object now has its own id field, but there is only one nextId field that isshared among all instances of the class. Let’s put it another way. If there are 1,000 objectsof the Employee class, then there are 1,000 instance fields id, one for each object. But there isa single static field nextId. Even if there are no employee objects, the static field nextId ispresent. It belongs to the class, not to any individual object.

NOTE: In most object -oriented programming languages, static fields are called class fields. The term “static” is a meaningless holdover from C++.

Let’s implement a simple method:

Suppose you set the employee identification number for harry:

Then, the id field of harry is set to the current value of the static field nextId, and the value of the static field is incremented:

Static variables are quite rare. However, static constants are more common. For example, the Math class defines a static constant:

You can access this constant in your programs as Math.PI.

If the keyword static had been omitted, then PI would have been an instance field of the Math class. That is, you would need an object of the Math class to access PI, and every Math object would have its own copy of PI.

Another static constant that you have used many times is System .out. It is declared in the System class as follows:

As we mentioned several times, it is never a good idea to have public fields, because everyone can modify them. However, public constants (that is, final fields) are fine.Because out has been declared as final, you cannot reassign another print stream to it:

NOTE: If you look at the System class, you will notice a method setOut that lets you set System.out to a different stream. You may wonder how that method can change the value of a final variable. However, the setOut method is a native method, not implemented in the Java programming language. Native methods can bypass the access control mechanisms of the Java language. This is a very unusual workaround that you should not emulate in your own programs.

Static Methods

Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression

computes the power xa. It does not use any Math object to carry out its task. In other words, it has no implicit parameter.

You can think of static methods as methods that don’t have a this parameter. (In a nonstatic method, the this parameter refers to the implicit parameter of the method

Because static methods don’t operate on objects, you cannot access instance fields froma static method. But static methods can access the static fields in their class. Here is anexample of such a static method:

To call this method, you supply the name of the class:

Could you have omitted the keyword static for this method? Yes, but then you wouldneed to have an object reference of type Employee to invoke the method.

NOTE: It is legal to use an object to call a static method. For example, if harry is an Employee object, then you can call harry.getNextId() instead of Employee.getnextId(). However, we find that notation confusing. The getNextId method doesn’t look at harry at all to compute the result. We recommend that you use class names, not objects, to invoke static methods.

You use static methods in two situations:

  • When a method doesn’t need to access the object state because all neededparameters are supplied as explicit parameters (example: Math.pow)
  • When a method only needs to access static fields of the class (example:

C++ NOTE: Static fields and methods have the same functionality in Java and C++. However, the syntax is slightly different. In C++, you use the :: operator to access a static field or method outside its scope, such as Math::PI.

The term “static” has a curious history. At first, the keyword static was introduced in C to denote local variables that don’t go away when a block is exited. In that context, the term “static” makes sense: the variable stays around and is still there when the block is entered again. Then static got a second meaning in C, to denote global variables and functions that cannot be accessed from other files. The keyword static was simply reused, to avoid introducing a new keyword. Finally, C++ reused the keyword for a third, unrelated, interpretation — to denote variables and functions that belong to a class but not to any particular object of the class. That is the same meaning that the keyword has in Java.

Factory Methods

Here is another common use for static methods. The NumberFormat class uses factory methodsthat yield formatter objects for various styles.

Why doesn’t the NumberFormat class use a constructor instead? There are two reasons:

  • You can’t give names to constructors. The constructor name is always the same asthe class name. But we want two different names to get the currency instance andthe percent instance.
  • When you use a constructor, you can’t vary the type of the constructed object. Butthe factory methods actually return objects of the class DecimalFormat, a subclass thatinherits from NumberFormat

The main Method

Note that you can call static methods without having any objects. For example, younever construct any objects of the Math class to call Math.pow.

For the same reason, the main method is a static method.

The main method does not operate on any objects. In fact, when a program starts, therearen’t any objects yet. The static main method executes, and constructs the objects that theprogram needs.

TIP: Every class can have a main method. That is a handy trick for unit testing of classes. For example, you can add a main method to the Employee class:

If you want to test the Employee class in isolation, you simply execute

If the employee class is a part of a larger application, then you start the application with

and the main method of the Employee class is never executed.

The program in Listing below contains a simple version of the Employee class with a static fieldnextId and a static method getNextId. We fill an array with three Employee objects and then printthe employee information. Finally, we print the next available identification number, to demonstrate the static method.

Note that the Employee class also has a static main method for unit testing. Try running both

java Employee and javaStaticTest to execute both main methods.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics