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 .

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