Static Keyword in Java
In Java, the static
keyword is used to declare members (variables and methods) that belong to the class itself, rather than to any specific instance of the class. When a member is declared as static
, it means that the member is shared among all instances of the class, and it can be accessed using the class name itself.
Here are some key points to understand about the static
keyword:
Static Variables (Class Variables):
Static variables are declared using the
static
keyword and are shared among all instances of the class.They are initialized only once, at the start of the program execution, and remain in memory throughout the program's lifespan.
Static variables are accessed using the class name followed by the variable name.
Example:
class MyClass { static int count; // Static variable // CODE... } // Accessing the static variable int x = MyClass.count;
Static Methods:
Static methods are associated with the class itself, rather than with any particular instance of the class.
They are declared using the
static
keyword and can be invoked using the class name, without creating an object of the class.Static methods cannot access instance variables directly because they do not belong to any specific instance.
A static method can access static data members and can change their value of it.
Example:
class MyClass { static void myStaticMethod() { // Static method // CODE... } } // Invoking the static method MyClass.myStaticMethod();
Restrictions for the static method
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
Static Blocks:
Static blocks are used to initialize static variables or perform other static initialization tasks.
They are executed only once, when the class is loaded into memory, before any static method or static variable is accessed.
Static blocks are defined inside the class and are enclosed in curly braces
{}
and preceded by thestatic
keyword.Example:
class MyClass { static { // Static block // Initialization or other tasks } }
Static Nested Classes:
A static nested class is a nested class that is declared with the
static
keyword.It can be accessed using the class name, without creating an instance of the outer class.
Static nested classes are often used for grouping related utility methods or encapsulating helper classes.
Example:
class OuterClass { static class StaticNestedClass { // CODE... } } // Accessing the static nested class OuterClass.StaticNestedClass nestedObj = new OuterClass.StaticNestedClass();
The static
keyword allows for the creation of class-level variables and methods that are not tied to any specific instance of the class. They can be accessed and used without the need to create an object, providing convenience and flexibility in certain programming scenarios.