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

℡╲_俬逩灬. 提交于 2019-12-04 23:25:30

问题


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

回答1:


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



回答2:


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.




回答3:


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.




回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/9634224/what-is-the-meaning-of-static-in-a-method-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!