In this comprehensive guide, we will delve into the various aspects of the static keyword in Java.
static keyword in Java indicates that the particular member belongs to a type itself, rather than to an instance of that type.
static as a non access modifier is used for:
- variables
- methods
- block initializers
- nested classes
static variables(class variables)
- static variables a.k.a class variables are variables created at class level and shared across all instances of that class.
- static variables are initialized when the class is loaded into JVM. These are loaded into a special area called Permanent Generation or PermGen for pre Java 8 versions and in Metaspace after Java 8.
- static variables can be directly accessed using the class name. We don’t need to have a instance of the class to access a static variable.
- Java Compiler gives you a warning ” The static field ABCD.xyz should be accessed in a static way” if you use an instance variable to access the static variable.
Let’s see how we have used static variable in the below example.
package com.java.core;
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String studentDetails() {
return "Student name :" + name + " ,School Name:" + schoolName;
}
static String schoolName = "Modern School";
public static void main(String[] args) {
Student student1 = new Student("Gyan");
Student student2 = new Student("Vivek");
System.out.println(student1.studentDetails());
System.out.println(student2.studentDetails());
}
}
Student name :Gyan ,School Name:Modern School
Student name :Vivek ,School Name:Modern School
static variables can also be accessed outside the class(provided it is not private) by directly using the class name.
package com.java.core;
public class TestStatic {
static void methodStatic() {
System.out.println(OtherClass.name);
}
public static void main(String[] args) {
TestStatic.methodStatic();
}
}
class OtherClass {
static String name = "Gyan";
}
Output
Gyan
static methods(class methods)
- Just like the static variables, static methods also belong to a class instead of the object, and so they can be called without creating the object of the class in which they reside.
- static methods are also widely used to create utility or helper classes so that they can be obtained without creating a new object of these classes.
- The biggest example is the “static main method” which we always use to start the execution of a program
package com.java.core;
public class TestStatic {
static void methodStatic() {}
public static void main(String[] args) {
TestStatic.methodStatic();
}
}
Things to Note
- Java Compiler gives you a warning ” The static method xyz() from the type ABCD should be accessed in a static way” if you use an instance variable to access the static method.
- We cannot refer to this or super inside a static method.
static block initializers
package com.java.core;
public class TestInitializer {
static {
// This is static initializer block
System.out.println("Static Block");
}
{
// This is instance initializer block
System.out.println("Instance Block");
}
TestInitializer() {
// This is constructor
System.out.println("Constructor");
}
public static void main(String[] args) {
TestInitializer testInitializer = new TestInitializer();
}
}
Static Block
Instance Block
Constructor
Few Things to Note
- A class can have multiple static blocks
- static blocks and static variables are executed in order they are present in a program.
static nested classes
We can create a class within a class.
- nested classes that are declared static are called static nested classes
- nested classes that are non-static are called inner classes
package com.java.core;
public class TestStatic {
static class NestedStaticClass {
public void method() {
System.out.println("method invoked");
}
}
class InnerClass {
public void innermethod() {
System.out.println("innermethod invoked");
}
}
public static void main(String[] args) {
// You can directly instantiate nested static class
NestedStaticClass nestedStaticClass = new NestedStaticClass();
nestedStaticClass.method();
TestStatic testStatic = new TestStatic();
// instantiation of inner class
TestStatic.InnerClass innerClass = testStatic.new InnerClass();
innerClass.innermethod();
}
}
Output
method invoked
innermethod invoked
Few Things to Note
- static nested classes do not have access to any instance members of the enclosing outer class; it can only access them through an object’s reference
- static nested classes can access all static members of the enclosing class, including private ones
- Java programming specification doesn’t allow us to declare the top-level class as static; only classes within the classes (nested classes) can be made as static
- We don’t need to create an instance of Outer class for creating an instance of the static class.
Challenges with the static keyword in Java:
- Increased Coupling: Excessive static usage leads to increased coupling between components, making the code harder to maintain.
- Limited Flexibility: Static members lack flexibility as they are shared across all instances of a class.
- Difficulty in Unit Testing: Testing can be challenging due to the global nature of static members.
- Thread Safety Concerns: Concurrent access to static variables can lead to thread-safety issues.
- Dependency Management: Overuse of static can result in tight coupling and hinder effective dependency management.
- Inheritance Limitations: Static members cannot be overridden in subclasses, limiting customization.
To mitigate these challenges, it is important to use the static keyword in java judiciously and follow best practices such as encapsulating shared state, employing proper synchronization mechanisms, and favoring instance-level variables and methods when appropriate.
By carefully considering the implications of using the static keyword, developers can create more maintainable, flexible, and testable Java code.
Conclusion
The static keyword in Java plays a vital role in defining and accessing class-level members. It provides convenience, efficiency, and flexibility in programming by allowing the creation of shared variables, methods, initialization blocks, and nested classes.
However, it is essential to use the static keyword in Java judiciously, as overuse or improper usage can lead to potential pitfalls, such as increased memory usage and potential thread-safety issues.
Also Read : Static imports in Java