Static Function in Java
In Java, the static keyword can be used with variable, constant, and functions. The main purpose of using the static keyword is to manage the memory so that we can use the memory efficiently. In this section, we will discuss the static function in Java.
If the keyword static is prefixed before the function name, the function is called a static function. It is often called a method.
A method is a group of variables and statements that functions together as a logical unit. Like fields, methods can have modifiers (like private, public, or static). Methods also have a return type (may be void if the method returns nothing). The return type can be a reference type (such as an object or an array). A method can have any number of parameters or arguments.
When a function is static, it is really part of the class and not part of the individual objects in the class. It means that static functions exist even before creating any objects.
The best example of a static method is the main() method.
Properties of Static Function
Declaring a Static Function
The declaration of a static function in Java is the same as the declaration of a method. The function has two parts function prototype and body of the function.
The function prototype contains the function signature that includes the function name, return type, access specifier, and the parameters list. The function body contains the logic or functionality to be performed.
In the above syntax, the access specifier and the parameter list are optional. A function may or may not have a parameter list. For example:
Calling Static Function
In Java, we cannot call the static function by using the object. It is invoked by using the class name.
Example of Static Function in Java
Let's create a Java program from which we can clearly understand the difference between static and non-static functions.
A non-static function is called. The static function is called.
Let's create a Java program and call a static method from another static method even without creating an object of the class.
Output:唔小东西你怎么这么紧 h唔小东西你怎么这么紧 h,稳如泰山心不乱是什么生肖稳如泰山心不乱是什么生肖,戏里戏外一叶孤舟popo戏里戏外一叶孤舟popo
Cube of 7 is: 343
Restrictions of the Static Method
There are two main restrictions for the static method. They are: