Program A Day: Static Methods

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

What is a static method?
How do static methods differ from instance methods?
Why use static methods?
What are some examples of static methods?

 

SideSectionTitle

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

A static method is a method associated with a class, rather than an object.
Static methods cannot directly access the instance variables within a class, typically all data used by a static method is passed in as a parameter. Static methods also cannot call instance methods directly. Static methods do not require a class to be instantiated to use them. Static methods cannot use the this keyword.
Static methods are used when a method does not need to refer to an object's state(ie an instance), and are typically used for generic calculations. If an instance method were used, you would have to create a useless object in order to perform this work. Static methods are also used to access static data within a class, such as the number of times an object has been instantiated. Finally, static methods are somewhat more efficient since you are not creating unneccessary objects, and the compiler does not need to pass an implicit object parameter to the method.
Examples of static methods include main and several utility methods from the Math class.

Code

SolutionCode goes here. Please DO NOT put your code in <pre> tags!

Back to the Program-A-Day homepage