Why does a static method in java allow only finite or non-final variables in its method, but not static?

Why does a static method in java allow only finite or non-final variables in its method, but not static?

For example, I have the following method:

public static void myfunc(int somethig)
{                                      
  int a=10;                            
  final int b=20;                      
  static int c=30;   //gives Error why?
}
+3
source share
5 answers

Since each function in java must be inside a class, you can get the same effect by declaring fields in your class. This is the easiest way, and java language developers are very conservative. They will never add such a function when there is a more obvious and less complicated way to do the same.

EDIT: I think philosophical functions are not the first class in java. They should not store data. There are classes, and they do it.

-1
source

Question: why not?

: ?

, :

public class Foo {
    static int bar = 21;
    public void foo() {
        static int bar = 42;  // static local
        return bar;
    }
}

:

public class Foo {
    static int bar = 21;
    private static foo$bar = 42;  // equivalent to static local
    public void foo() {
        return bar;
    }
}

, () .

Java, , , , . (, , .)

+11

Java ( - ) . , .

+3

. .

However, you can have a static field in your class.


Resources:

+2
source

You cannot have a static variable. There is no such. Instead, you can use the class variable as static.

+1
source

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


All Articles