A class member must be accessed only in conjunction with an object of its class. However to create a member that can be used by itself, without reference to a specific instance.
For that declare member as a static with keyword static. The static member can be accessed before any objects of its class are created, and without reference to any object. For ex : main () is declared as static because main() called by JVM before any object of the class exists and therefore must be called independent of any object.
Static instance variables are essentially global variables. The static variable does not create other copy, all instances of the class share the same static variable.
static variable referred to as class variable and static method is referred to as class method.
Java creates only one copy for a static variable which can be used even if the class is never actually instantiated.
Methods declared as Static have several restrictions.
- They can only call other Static methods.
- They must only access Static data.
- They cannot refer to this or Super in any way.
Calling static methods
There are two cases of calling static methods.
1. Called from within the same class
2. Called from outside the class
1. Called from within the same class
2. Called from outside the class
Called from within the same class
Just write the static method name.
Called from outside the class
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. It takes following format.
classname.membermethod()/memeber variable
Accessing static variables
Although a
static
method can't access instance variables, it can access static
variables. A common use of static
variables is to define "constants". Examples from the Java library are Math. PI
or Color.RED
. They are qualified with the class name. Any method, static
or not, can access static variables. Instance variables can be accessed only by instance methods. - Posted by : Ruchita Pandya
No comments:
Post a Comment