STATIC KEYWORD:
•Static:
>member belongs to a class(type), not to an instance of the class(object).
>only one instance of that static member(attribute/method) is created
and shared across all instances of the class.
>static keyword: used for memory management.
------------------------------------------------------------------------------
•Static Variables & Methods:
>get memory only once in the class area at the time of class loading.
-->available for use without instantiation.
------------
-STATIC VARIABLES:
>refer to common property of all objects (not unique for each object).
--> class: employee - attribute: company name = XYZ
--> all objects of employee class (=employees) have company name = XYZ
>retain its value when it is changed (don't go back to first value).
-->used with counters
+It makes program memory efficient.
--->Static Variables used when SHARING DATA.
>Declaration(example):
-----------------------------------------
public class Employee
{
int ID;
String name;
static String company = "XYZ";
//constructor
public Employee(int ID, String name)
{
[Link]=ID;
[Link]=name;
}
...
}
-----------------------------------------
-constructor parameters do not contain the static variables.
-we can change static variables in the MAIN method:
-->[Link] = "ABC";
------------
-STATIC METHODS:
>belong to the class not to objects of the class.
>only access static variables and methods of the same or different class.
-->rewrite the values of any static data member.
--->Static Methods used when writing any UTILITY METHODS.
----
•Restrictions:
>cannot use non static data or call non-static methods.
>this & super keywords cannot be used in static context.
----
->Java MAIN method is static:
there is no class objects when the Java runtime starts.
-> the MAIN should be static (belongs to the class).
-> JVM call MAIN method without having to create an instance(object) of the
class.