In this article, we will discuss the differences between a static method and an instance method. Firstly, we will discuss the instance method and at the last, we will see the static method.
Instance methods are the methods defined under a class and we can call such functions only after creating an object of that class. In fact, the call to the instance method is made through the created object itself.
An instance method has generally the following structure:
Instance methods generally reside in the permanent generation space section of the heap but the local variables and parameters have a separate location in the stack memory. We can invoke instance methods within the same class or from a different class defined under the same package or different package if the access type allows the same.
Some of the properties of the instance method are the following:
- Instance methods are related to an object rather than a class as they can be invoked after creating an object of the class.
- We can override an instance method as they are resolved using dynamic binding during run time.
- The instance methods are stored in a single memory location.
Let us consider the following program illustrating the working of instance method:
An static method in Java is a method that can be called without creating an object of the class. We can reference such methods by the class name or direct reference to the object of that class.
Some of the properties of the static method are the following:
- An static method is related to a class rather than an object of the class. We can call the static method directly without creating an object of the class.
- Static methods are designed in such a way that they can be shared among all objects created using the same class.
- We cannot override static methods as they are resolved using the static binding by the compiler during compile time.
Let us consider the following program illustrating the working of static method:
Static versus instance methods
In this article, we discussed what is static and instance methods. We also saw their working in detail. The differences between these methods have also been highlighted in detail. We believe this article has surely enhanced your knowledge and strengthened your Java knowledge.