Reputation:
I want to understand what does the word 'static' do in the 'writeNumbers' method header?:
public class DisplayClass {
/**
* @param args
*/
public static void main(String[] args) {
writeNumbers();
}
public static void writeNumbers()
{
int count;
for(count=1; count<=20; count++)
{
System.out.println(count);
}
}
}
Upvotes: 6
Views: 16954
Reputation: 291
To clarify Crollster's answer, I wanted to point out 2 things.
First:
By class level, it means you can access it by typing in "DisplayClass.writeNumbers()", per your example in the question, without ever needing to use "new DisplayClass();".
Second:
By class level, it also means that the code base is not copied to any instances so you receive a smaller memory footprint.
Upvotes: 3
Reputation: 8530
static elements belong to class rather than Object.
so static method belongs to class which can be directly accessed like below.
public class MyClass{
public static void display(){
}
..
..
}
.
.
..
MyClass.display();
Upvotes: 1
Reputation: 2771
The term static
means that the method is available at the Class level, and so does not require that an object is instantiated before it's called.
Because writeNumbers
was being called from a method that was itself static
it can only call other static methods, unless it first instantiates a new object of DisplayClass
using something like:
DisplayClass displayClass = new DisplayClass();
only once this object has been instantiated could non-static methods been called, eg:
displayClass.nonStaticMethod();
Upvotes: 20
Reputation: 6090
Static tells the compiler that the method is not associated with any instance members of the class in which it is declared. That is, the method is associated with the class rather than with an instance of the class.
Upvotes: 0
Reputation:
From the Oracle Java Tutorial verbatim:
The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class...
Its you wouldn't have to instantiate a class to use the method in question. You'd feed that method the appropriate parameters and it'd return some appropriate thing.
Upvotes: 2