Saturday, 8 April 2017

Static Members (Static Methods )

Static Members (Methods, Variables, Static Block and Class)

Static Method


In JAVA, Variables can be declared with the "static" keyword.

Syntax: <class-name>.<method-name>
Example: Student.getName();

A static method can only call only other static methods, i.e. they 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 to all it.

A static method cannot refer to this or super keywords in anyway.

A static method can access only static data. It can not access non-static data (instance variables)

Static Members (Static variables / Class variables)

Static Members (Methods, Variables, Static Block and Class)

Static Variable

In JAVA, Variables can be declared with the "static" keyword.
Example: static int x = 0;
When a variable is declared with the keyword "static", its called a class variable. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create an instance.
So a static variable is common to all the objects and can be accessed without using a particular object.
They belong to the class rather than an object, hence they are also known as class variables.