Static Members in Java


Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. It is a method which belongs to the class and not to the object(instance).

  • A static method can access only static data. It cannot access non-static data ( instance variables ) .
  • A static method can call only other static methods and cannot call a non-static method from it .
  • A static method can be accessed directly by the class name and doesn’t need any object .

The program demonstrates the usage of static variables and methods in Java. In the staticTest class, there are two variables defined - a which is declared as static and b which is an instance variable. There are two methods defined in the class - show() which is an instance method and display() which is a static method.

In the main method of the stat_vari_methods class, two objects of the staticTest class are created - o1 and o2. The show() method is called on o1 which prints the values of a and b (which are 10 and 20 respectively). Then, the value of b in o2 is changed to 100 and the value of a is changed to 200. The show() method is called on o2 which prints the updated values of a and b. Finally, the show() method is called on o1 again which prints the original values of a and b (since a is a static variable and was updated to 200, the new value is reflected in all objects of the class).

Thus, the program demonstrates how static variables are shared among all instances of a class and how static methods can be called without creating an object of the class.

Source Code

//Static Variables and Static Methods
class staticTest
{
    static int a=10;
    int b=20;
    void show()
    {
        System.out.println("A : "+a+" B : "+b);
    }
    static void display()
    {
        System.out.println("A : "+a);
    }
}
public class stat_vari_methods {
    public static void main(String args[])
    {
        staticTest o1=new staticTest();
        o1.show();
        staticTest o2=new staticTest();
        o2.b=100;
        staticTest.a=200;
        o2.show();
        o1.show();
    }
}
 

Output

A : 10  B : 20
A : 200 B : 100
A : 200 B : 20
To download raw file Click Here

Basic Programs