A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
Static Method
A static method is also called a class method and is common across the objects of the class and this method can be accessed using class name as well.
Non-Static Method
Any method of a class which is not static is called non-static method or an instance method.
Following are the important differences between static and non-static method.
Sr. No. | Key | Static | Non-Static |
---|---|---|---|
1 | Access | A static method can access only static members and can not access non-static members. | A non-static method can access both static as well as non-static members. |
2 | Binding | Static method uses complie time binding or early binding. | Non-static method uses run time binding or dynamic binding. |
3 | Overriding | A static method cannot be overridden being compile time binding. | A non-static method can be overridden being dynamic binding. |
4 | Memory allocation | Static method occupies less space and memory allocation happens once. | A non-static method may occupy more space. Memory allocation happens when method is invoked and memory is deallocated once method is executed completely. |
5 | Keyword | A static method is declared using static keyword. | A normal method is not required to have any special keyword. |
Example of static vs non-static method
JavaTester.java
public class JavaTester { public static void main(String args[]) { Tiger.roar(); Tiger tiger = new Tiger(); tiger.eat(); } } class Tiger { public void eat(){ System.out.println("Tiger eats"); } public static void roar(){ System.out.println("Tiger roars"); } }
Output
Tiger roars Tiger eats