| Author |
Static vs instance methods
|
Pallav Bora
Ranch Hand
Joined: Oct 13, 2009
Posts: 73
|
|
Hi,
I would like to know the difference between a static method and the same method defined as an instance method. I would like to know the difference in terms of performane and memory usage. Which one will be more efficient?
For example:
Method defined as static:
Class X
{
public static String getX()
{
return "ABC";
}
}
Same Method defined as instance method
Class X
{
public String getX()
{
return "ABC";
}
}
Thanks
|
 |
Brad Dwan
Ranch Hand
Joined: Apr 22, 2010
Posts: 62
|
|
If you define a static method within a class, you no longer need to create said object before you call that particular method.
Google is your friend.
|
-Nev
"It's about choosing your battles, not fighting somebody else's war"
|
 |
senthil kumar. J
Greenhorn
Joined: May 04, 2010
Posts: 5
|
|
By having a static method, it belongs to the class unlike instance method which belong to object that class.
In terms of performance and memory usage, static methods as said does not require you to create class object in order to access them but that does not mean its efficient too many static methods and static variables creates memory problem.
Overall use of static method and instance variables is based on type of requirement, say you want to have a utility like method in such case static method would be ideal while in other cases instance variable would fine as you will not have certain constraints as in static method
- static method can only call other static methods
- A static method must only access static data
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32827
|
|
|
The important thing is that static members don't belong to an object.
|
 |
 |
|
|
subject: Static vs instance methods
|
|
|