purpose of static members

A member of a class may be delcared as static.

A static member, is associated with the class(in which it is delcared), and not with the indidvidual objects.
Since static members are associated with class, they can be directly accessed with class name.
static members can be accessed, even before creation of object of the class.

A data members declared as static has common storage and value for the class, i..e for all objects of the class.

From a non static method both static and non static data members and member methods can be used or invoked.
Where as from static method only static members can be used or invoked. So, to invoke non static methods, from a static method, we need to create object of class, whose method need to be invoked.

this keyword cannot be used in static methods, as both of them contradict. static is unrelated to object, where as this refers to current object.

static example

//Example of static keyword
class Abcd
	static public int i;
	//i value is common to all object of Abcd
	//static members are associated with class, and not with object

	int j;
	//each object of Abcd, can have different value of j

	public int getI()
	return i;

	public int getJ()
	return j;

	//static data members/methods can be used in non static methods
	//but a static method can refer only static methods or data members
	public static void stTest()

	System.out.println("This is static method");
	//j = 10; //error, only static variables can be referenced

public class StaticExample {

	float met1()
	return 0.0f;

	public static void main(String args[])
	Abcd.i = 50;

	//Abcd.j = 20;
	//Compile error, j cannot be accessed directly with class name
	//because j is non static

	StaticExample se = new StaticExample();


	Abcd obj = new Abcd();
	//obj.j = 34;
	//obj.i = 20;

	System.out.println("Abcd.i is "+Abcd.i);
	System.out.println("obj.j is "+obj.j);

You may also like to read:
this keyword
How to declare static block
Are static constructors possible?
purpose of static method in abstract class

One thought on “purpose of static members”

Leave a Reply