• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Vs Non Static Methods

 
Mahi Ranga
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

When we go for Static method and When we go for Non Static method in Java.
 
Sumit Patil
Ranch Hand
Posts: 296
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this earlier post

Also, Carefully Choose One Forum
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
GENERALLY speaking...

Static methods can be used when no object needs to be created. For example, the methods of the Math class are all static. I don't need a Math object to find the cosine of pi/4, i just need to pass it the value.

a Non-static method is used when the state of an object is important. If I have a Dog class, it may have a setName() method. You can't setName if there is no Dog created. Even if there were thousands of Dog objects, you need to call setName() on a SPECIFIC dog.

So, you'd make it a non-static method of the class. The you can only call it when you have a Dog object created:

Dog myDog = new Dog();
myDog.setName("Mamie");


note: corrected mistake Campbell kindly pointed out
 
Campbell Ritchie
Sheriff
Pie
Posts: 49823
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest: default to instance (not static) methods until proven otherwise.
Consider a static method when you want it to access, read, display or use nothing from the object, and you want to write alter or record nothing in the object. Consider a static method if you need to call it before any objects exist. If you are overriding or want to override or are implementing an interface, then your method must not be static.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
fred rosenberger wrote: . . .
Dog myDog = new Dog();
myDog.setName = "Mamie";
Surely that’s… where setName() is not static.

crap...yes...
that's why i never write code first thing in the morning...
 
Campbell Ritchie
Sheriff
Pie
Posts: 49823
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First thing in the morning? It’s after 4pm. The only time to write code is 2am

It is a good explanation, though.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic