8.1 Static Class Members

In Java you can create a field or method that does not belong to any object of a class. Such are known as static variables or static methods.

Static Variable

To declare a static variable, you put them in the class just like instance variables, but you put the keyword static in front. Static variables belong to the class and has one copy. When a value is stored in a static variable, it is not stored in object of the class. Static variables are useful to keep information that is common to every object.

Program (Example.java)

/** * This class demonstrates a static field. */ public class Example { private static int staticField = 0; private int instanceField; /** * The constructor increments the static field and * initialize instance field */ public Example(int i) { instanceField = i; staticField++; } /** * The show method display the value * in the staticField and instanceField */ public void show() { System.out.println("Value of Static Field " + staticField + "

Value of Instance Field " + instanceField); } }

Program (ExampleDemo.java)

/** * Program to test the Example class. */ public class ExampleDemo { public static void main(String[] args) { Example one = new Example(3); System.out.println("Value of one.show() : "); one.show(); Example two = new Example(5); System.out.println("Value of two.show() : "); two.show(); } }

Output : Value of one.show() :

Value of Static Field 1

Value of Instance Field 3

Value of two.show() :

Value of Static Field 2

Value of Instance Field 5

Static Methods

A static method can be accessed by using the name of the class. So you don't need to create an instance to access the method



Program (MyMath.java)

/** * This class demonstrates static methods. */ public class MyMath { /** * The cube method returns the cube of * the number passed into parameter. */ public static int cube(int number) { return number * number * number; } }

Program (MyMathDemo.java)

/** * This program demonstrates the MyMath class. */ public class MyMathDemo { public static void main(String[] args) { // Display the cube of number. System.out.println("cube of 3 is " + MyMath.cube(3)); } }

Output :

cube of 3 is 27