A static method in Java is a method that belongs to a class rather than an instance of a class. This means you can call a static method without creating an object of the class. Static methods are sometimes called class methods. Here are some key features of static methods:
- They are part of a class rather than an instance of that class.
- They can be accessed without creating an instance of the class.
- They have access to class variables (static variables) without using the classs object (instance) .
- Only static data may be accessed by a static method.
Static methods can be used to create utility classes that contain general-purpose methods, and they can be used to enforce encapsulation since they can only be called from within the class in which they are defined. To create a static method in Java, you use the static keyword. Here is an example of how to create a static method in Java:
public class MyClass {
public static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
}
In this example, myStaticMethod()
is a static method, while myPublicMethod()
is a non-static method. You can call myStaticMethod()
without creating an object of the class, but you must create an object of the class to call myPublicMethod()
.