My GitHub
In Java, static
it is a keyword used to indicate that a member (variable, method, nested class, etc.) belongs to the class, rather than belonging to a specific instance of the class. In short, static
members are at the class level, not the instance level. Here are some uses static
of the keyword:
static variable
A static
variable is associated with a class, not an instance. All instances of this class share the same static
variable.
class MyClass {
static int staticVar = 0;
}
static method
A static
method belongs to the class, not to any specific instance. Therefore, it cannot access non- static
members of the class.
public class HelloWorld {
static void sayHello() {
System.out.println("Hello, World!");
}
}
static block
static
Block is used to initialize static
variables, which is only executed once when the class is loaded.
class MyClass {
static int staticVar;
static {
staticVar = 10;
System.out.println("Static block executed");
}
}
static inner class
You can also define an static
inner class that cannot access non-members of the outer class static
.
public class OuterClass {
static class StaticNestedClass {
// body of static nested class
}
}
Why use static?
- Sharability : Use
static
variables to share data between all instances. This is typically used for constants or configuration data. - No instances required :
static
methods and variables can be accessed and modified before any instances are created. - Tool methods :
static
often used to store tool methods that do not depend on instance state (such asMath.abs()
). - Saves memory : Since
static
the data is not part of each instance, usingstatic
can save memory.
Precautions
- Use caution when using
static
the keyword becausestatic
variables are shared across all instances, which can lead to errors that are not easily traceable. - Since
static
methods cannot access non-static
members, they cannot be overridden by subclasses.
Overall, static
a very useful keyword but one that needs to be used with caution. Understanding how it works and applicable scenarios is very important for Java programming.