“Static” methods in Java are declared using the “static” keyword and are used to apply the functionalities that are not related to any object. These methods represent the class’s state rather than the object’s state. This resultantly makes the static methods independent of instance creation of the class, thereby reducing the code complexity. As a result, these methods are also called “class methods”.
Contents Overview
- What is a Static Method in Java?
- Features of Static Methods
- Advantages of Static Methods
- Restrictions on Static Methods
- When to Use the Static Methods?
- Difference Between Static and Non-Static Methods in Java
- Why is the “main” Method in Java Static?
What is a Static Method in Java?
A “static” method in Java refers to a method that is related to a class instead of a class instance. It is such that this method can be invoked without creating a class instance/object.
Syntax(Declaration of Static Method)
Access_mod static void display(){
// Method's Body
}
In this syntax, “Access_mod” is the access modifier that can be “public”, “private” etc, and “display()” is the static method’s name.
Syntax(Invoking of Static Method)
Class.static_method_name()
staticmethodname()
In the former syntax, “class” represents the class’s name in which the static method i.e., “static_method_name()” is defined.
Features of Static Methods
- Static methods can be used to enforce encapsulation as they are invoked from the class.
- All the class instances have access to these methods.
Advantages of Static Methods
Following are some advantages of using the static methods:
- Efficient than the non-static methods.
- These methods can be invoked from anywhere in the code.
Restrictions on Static Methods
- Only static data can be accessed by the static method.
- The “this” and “super” keywords cannot be used in a static environment.
When to Use the Static Methods?
The “Static” methods can be used and are effective in the following scenarios:
- When there is a need to apply the functionalities independent of any class’s instance such as mathematical calculations.
- When a code implementation of a method is not affected by the class’s instances.
- Creating utility classes which are the classes that only contain the static methods.
Difference Between Static and Non-Static Methods in Java
Static Methods | Non-Static Methods |
---|---|
The static methods can be invoked from outside the class directly in which they are defined. | The non-static methods cannot be invoked from outside the class directly. Rather, a class object is required to access them. |
These methods execute when an object of the class is created. | These methods do not execute upon the creation of the class’s instance. |
Subclasses can override the static methods | This is not the case with the non-static methods. |
These methods are related to the class. | The non-static methods, however, are related to a class’s instance. |
The static methods cannot be overridden. | The non-static methods, however, can be overridden. |
Example 1: The “Static” Method Cannot Invoke the Instance Variable
In Java, JVM first executes the “static” method and then the class objects are created. It is such that the static method is accessed directly regardless of the instance variable therefore, the instance variable is not required by the static method.
Below is the demonstration:
package jbArticles;
public class Static {
static int x = 2;
int y = 6;
void out() {
System.out.println(x);
System.out.println(y);
}
static void outStatic() {
System.out.println(x);
}
public static void main(String[] args) {
Static object = new Static();
object.out();
outStatic();
}}
In this block of code, consider the following steps:
- Within the public class “Static”, initialize a static and a non-static variable, respectively.
- Now, define a non-static method “out()” that prints the defined integer values.
- Also, declare a static method “outStatic()” that prints the former defined integer value.
- In “main”, create a class instance using the “new” keyword and the “Static()” class constructor.
- Finally, invoke the non-static method via the created object and access the static method directly.
Output
In this output, it can be seen that the defined integer values are printed as per their print statements in the non-static and static methods, respectively.
Alternatively, the static method can also be invoked by pointing to the class in which it is defined, demonstrated below:
Bonus Tip: The static methods cannot access the non-static methods, however, it is not the case the other way around.
Example 2: Restrictions on Static Methods in Java
There are also some restrictions on the static methods. For instance, this method cannot access the instance member as well as the class methods.
Since the static methods are invoked without an object and the instance variables and methods of the class are accessed with the help of a class object. Therefore, accessing a non-static method, variable, etc within the static method returns an error:
package jbArticles;
public class Static {
static int x = 2;
void out() {
System.out.println(x);
}
static void outStatic() {
out();
System.out.println(x);
}
public static void main(String[] args) {
outStatic();
}}
The code explanation is as follows:
- Within the public “Static” class, initialize a static variable representing an integer value.
- Define the non-static method “out()” that prints the defined static integer without any error.
- After that, declare the static method “outStatic()” that accesses the non-static method “out()” and also prints the static integer.
- In “main” invoke the static method directly.
Output
From this error output, it can be analyzed that a non-static method cannot be invoked by the static method.
Let’s apply the same concept to the non-static variable such that a static method invokes a non-static variable, demonstrated below:
As seen, the same error is returned.
Example 3: Implementing the Singleton Design Pattern Using Static Method
The following code implements the singleton design pattern. This is useful in managing resources like database connections or thread pools. The below example ensures that there is only a single connection to the database at a time:
package jbArticles;
public class Static {
private Static() {}
private static Static instance = null;
public static Static getInstance() {
if (instance == null) {
instance = new Static();
}
return instance;
}}
In this snippet of code:
- The “Static” class’s constructor is assigned as “private” to make sure that this class cannot be instantiated by any other classes.
- Also, a static method for returning the class’s instance and a class’ static instance is defined.
- The “getInstance()” method analyzes if an object of the class is created/made. If not, it is created and returned by the method.
- This means that only a single instance/object of the “Static” class can exist at a time.
Note: The “Static” method can be overloaded but cannot be overridden. Let’s demonstrate both these approaches individually.
Example 4: Overloading the Static Method in Java
“Overloading” is the procedure in which the method having the same name is repeated with different parameters within the class. This code example overloads the static method:
package jbArticles;
public class Static {
public static void out() {
System.out.println("This is Harry");
}
public static void out(int x) {
System.out.println(x);
}
public static void main(String[] args) {
out();
out(2);
}}
In these code lines, consider the below-explained steps:
- Within the public class “Static”, define a static method “out()” without any parameters that print the given statement.
- Moving forward, overload the static method by creating another method of the same name i.e., “out()” but with a parameter representing an integer value.
- In “main”, invoke the default static method and the overloaded method(by passing the integer as its argument).
Output
Here, it can be seen that overloading the method resulted in a streamlined outcome.
Example 5: Overriding the Static Method
“Overriding” is done in inheritance such that a child class’s method overrides the parent class’s method by having the same name. In this example, the static method will be overridden:
package jbArticles;
class Base {
public static void display() {
System.out.println("Static Method of Parent Class");
}
public void print() {
System.out.println("Non-static Method of Parent Class");
}}
class Derived extends Base {
public static void display() {
System.out.println("Static Method of Child Class");
}
public void print() {
System.out.println("Non-static Method of Child Class");
}}
public class Static {
public static void main(String[] args) {
Base object = new Derived();
object.display();
object.print();
}}
Based on this code, consider the following explanation:
- Define a parent class “Base” that contains the static method “display()” and a non-static method “print()”, respectively.
- Now, create a child class “Derived” inherited from the parent class “Base” using the “extends” keyword.
- In its definition, override the static method “display()” and likewise, override the non-static method “print()” as well.
- In “main”, create an instance of the child class “Derived” by referring to the parent class “Base” and invoke the overridden static “display()” and non-static “print()” methods.
Output
From this output, it can be observed that the static method is not overridden. Instead, the static method i.e., “display()” from the parent i.e., the “Base” class is invoked whereas the non-static method is overridden appropriately.
Bonus Query: Why is the “main” Method in Java Static?
The “main()” method in Java is static to invoke the static method without creating an instance/object. It is such that if it was non-static, an object would be needed before invoking the “main()” method, which would result in extra memory allocation.
Conclusion
A “Static” method in Java refers to a method that is related to a class rather than a class instance. It is such that this method can be accessed without creating a class object/instance. This method can be used to invoke the static data only and is helpful to enforce encapsulation or implement a singleton design pattern. Moreover, this method can be overloaded but can not be overridden.