This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes static and non static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static and non static" Watch "static and non static" New topic
Author

static and non static

Khurram Ajmeri
Greenhorn

Joined: Nov 24, 2001
Posts: 6
what is the difference between static and non static methods? :roll:
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Static methods are class related. You do not need an actual object of the class to invoke them.
Notice that all of the methods of the class Math are static. That way you do not need to make a little Math object just to use the method of the class.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Khurram
The basic difference is that static methods belong to the class while non-static ones belong to individual objects. The best example of static methods is in the Math class the methods in Math don't need a Math object to work, you just call the method and supply the arguments and the method does it job, there is no instance of Math passed to the method (no 'this'). Static methods normally work with static variables of the class.
On the other hand non-static methods need an instance of that class to work on. An example would be a class that keeps track of the number of instances in existence:

In the PublicLibrary consructor every time a library is created we can increment the numberOfLibraries variable. And at any time we can call
PublicLibrary.numberOfLibraries();
to get the number of libraries created. The numberOfLibraries is independent of any specific instance of PublicLibrary.
The getNumberOfBooks method on the other hand is not a static method so it needs a current instance of the class to act on. The 'this' in that method is not really needed, I put it there to show that the non-static methods actually have an instance of the class to work with, as opposed to the static methods that don't need one.
hope that helps, if not let us know what you're still confused on...


Dave
 
Don't get me started about those stupid light bulbs.
 
subject: static and non static