STATIC VARIABLES AND METHODS
The static keyword can be used in 3 scenarios
static blocks of code.(SIB)
Let's look at static variables and static methods first. Static block of code is explained in SIB
Static fields are initialized at time of class loading, opposite to instance variable which is initialized when instance of the particular class is created..
Binding of static variable will happen at compile time.
Declaring same static method of parent class in child class is known as method hiding in java.
If we try to override a static method with a non-static method in child class, will get compilation error..
If we don't synchronize static variables properly, it will result in race condition.static.
When a number of objects are created from the same class, each instance has its own copy of class variables. But this is not the case when it is declared as static.
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once, at the start of the execution.These variables will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn't need any object
Syntax : <class-name>.<variable-name>
In above example, we have one static variable named "country Counter" so whenever we are creating one new object,its value will be incremented by 1 as counter variable is being shared by all country objects and we have instance variable named "dummy Counter" so whenever any new object is created, its value is initialized to 0 again.
It is a method which belongs to the class and not to the object(instance)A static method can access only static data. It can not 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
Syntax : <class-name>.<method-name>
A static method cannot refer to “this” or “super” keywords in anyway
Main method is static, since it must be accessible for an application to run, before any instantiation takes place.
Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable.
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. (The keyword super relates to inheritance.)