Static VS Non static methods in Java
Static and non-static methods in Java are two different types of methods that serve different purposes. Here's a breakdown of their differences:
- Static Method:A static method belongs to the class itself and not to any specific instance of the class. It can be called using the class name directly without creating an instance of the class.
- Non-Static Method:A non-static method, also known as an instance method, is associated with a specific instance or object of a class. It can be called only through an instance of the class.
- Static Method:Method: Static methods can be accessed using the class name directly, followed by the method name. For example: ClassName.staticMethod().
- Non-Static Method:Non-static methods can only be accessed through an instance of the class. For example: instanceName.nonStaticMethod().
- Static Method:Static methods are loaded into memory when the class is loaded, and they remain in memory throughout the execution of the program. They are stored in a special area called the "Method Area" or "Permanent Generation" (prior to Java 8) or "Metaspace" (from Java 8 onwards).
- Non-Static Method:Non-static methods are associated with objects or instances of a class. When an instance of the class is created, memory is allocated for the instance variables and non-static methods within that instance.
- Static Method:Static methods are commonly used for utility functions or operations that do not require access to instance-specific data. They can be called directly by other static methods or used to perform class-level operations.
- Non-Static Method:Non-static methods are typically used to manipulate or access instance-specific data and perform operations specific to individual objects.
Access to Members
- Static Method:Static methods can only directly access other static members (variables or methods) of the class. They cannot access non-static (instance) variables or methods directly. However, they can create an instance of the class and access non-static members through that instance.
- Non-Static Method:Non-static methods can directly access both static and non-static members of the class. They can refer to non-static variables and methods directly, without the need for any additional qualifiers.
It's Important to note that static methods cannot be overridden in subclasses, as the method resolution is based on the class itself rather than the instance. Non-static methods, on the other hand, can be overridden in subclasses to provide different implementations.Static example
Static methods are associated with the class itself, while non-static methods are associated with individual instances of the class. Static methods are called using the class name, while non-static methods require an instance of the class to be invoked.