Static & Non-static Methods in Java
A method in a collection of statements with a name/method name that are grouped in order to perform a task when it is called. Data, known as parameters can be passed into methods.
Classes provide methods that can perform common tasks on objects; most methods must be called on a speficic object. Also, many classes provide methods that perform common tasks and do not require objects. These methods are called STATIC METHODS. A static method is a method that belongs to the class rather than an instance of a class. A non-static method belongs to the object of a class (doesn't have keyword static before method name). A non-static method can access any static variable & any static method without creating an instance of the class because the static variable belongs to the class. Static method is accessible to every instance of a class, while methods that are defined in an instance can be accessed only by that member of a class.
The static method is called by using its class name, followed by (.) and the name of the method: ClassName.methodName(arguments).
Figure 1.1 static method |
For example on Figure 1.1, Calculate.java class has two static methods: product() and main (). The product() computes the products of two numbers (int x, int y) and main() interacts with the user.
The static method product() is called on main method using Calculate.product(5,3).
Figure 1.2 non-static method |
Figure 1.2 shows the non-static method being called on main. As shown, it doesn't contain the "static" keyword. If we would call the method the same way as before, it will get us an error, showing that our non-static method product (int,int) can't be referenced from s static context. That is why we need to create an instance and call the method from the new created instance.
Static method can call and manipulate only other static methods in the same class directly. Non-static instance variables cannot be accessed by them; it doesn't know which instance's variable to use. In order to access the class's non-static members, the static method must use a reference to an object of the class. Static methods relate to the class as a whole, while non-static methods are associated with a specific instance (object) of a class and may also manipulate the instance variable of that object.
Lot of objects of a class, each with its own copies of instance variables can exist at the same time. If we would want the static method to invoke a non-static method directly, the question is, how would the method know which object's instance variable to manipulate? So, Java doesn't allow static methods to access non-static members of the same class directly.