Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static vs instance methods

 
Pallav Bora
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
senthil kumar. J
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48445
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The important thing is that static members don't belong to an object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic