简体   繁体   中英

what is the meaning of 'static' in a method header?

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);
        }
    }
}

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();

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.

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.

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM