What is the meaning of “static” in the method header?

I want to understand what the word "static" does in the title of the writeNumbers method ?:

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); } } } 
+6
source share
5 answers

The term static means that the method is available at the class level, and therefore does not require the object to be created before it is called.

Since writeNumbers was called from a method that itself was static , it can only call other static methods, unless it creates an instance of a new DisplayClass object using something like:

 DisplayClass displayClass = new DisplayClass(); 

only after this object has been created can non-static methods be called, for example:

 displayClass.nonStaticMethod(); 
+20
source

From the Oracle Java Tutorial literally:

The Java programming language supports static methods as well as static variables. Static methods that have a static modifier in their declarations should be called with the class name, without the need to instantiate the class ...

To do this, you do not need to instantiate the class to use the method in question. You will feed this method with the appropriate parameters, and it will return some suitable things.

+2
source

To clarify Krollster’s answer, I wanted to point out 2 things.

At first:

By class level, this means that you can access it by typing "DisplayClass.writeNumbers ()," according to your example in the question, without having to use the "new DisplayClass ();".

Secondly:

At the class level, this also means that the code base is not copied to any instances, so you get less memory.

+2
source

static elements belong to the class, not to the object.

therefore, the static method belongs to a class that can be directly accessed, as shown below.

 public class MyClass{ public static void display(){ } .. .. } . . .. MyClass.display(); 
+1
source

Static tells the compiler that the method is not associated with any instance of the class class in which it is declared. That is, the method is associated with the class, not with an instance of the class.

0
source

Source: https://habr.com/ru/post/910321/


All Articles