Java 通过非静态方法更改公共静态变量

Java 通过非静态方法更改公共静态变量,java,static-variables,Java,Static Variables,我将在不同的环境中实现相同的功能。我想通过调用非静态方法更改静态变量的值,如下所示 public static staticVar = changetheStatic(); public String changetheStatic(){ return "valueChanged";` } 我得到了类似“将方法更改为静态”的错误。。所以,任何建议……这根本行不通 只能在某些实例上调用非静态方法。在你的例子中,没有实例;因此,编译器只允许您调用静态方法 我要说的是:命名很混乱。您调用了方法cha

我将在不同的环境中实现相同的功能。我想通过调用非静态方法更改静态变量的值,如下所示

public static staticVar = changetheStatic();
public String changetheStatic(){
return "valueChanged";`
}

我得到了类似“将方法更改为静态”的错误。。所以,任何建议……这根本行不通

只能在某些实例上调用静态方法。在你的例子中,没有实例;因此,编译器只允许您调用静态方法


我要说的是:命名很混乱。您调用了方法changeTheStatic()。但这种方法并没有改变任何事情。它只返回一个值。因此,您应该将其称为getInitialValue()之类的名称

你不能这么做。您正在尝试在不初始化对象的情况下调用实例方法。相反,您可以在构造函数中执行此操作

          public class A {
           public static staticVar ;

           public A() {
                  A.staticVar = this.changetheStatic()
           }
           public String changetheStatic(){
             return "valueChanged";`
           }
         }
如果不想在构造函数中更改它,只需初始化一个对象并调用实例方法即可

                System.out.println(A.staticVar);//old value
                new A().changetheStatic();//will call instant method related to the new instantiated object , note i did not give it a reference so GC will free it cuz i only need it to change the static variable

                System.out.println(A.staticVar);//new value
这里的整个想法是,您正在尝试将instant方法作为静态调用,instant方法需要从对象调用

         public static staticVar = changetheStatic();

因此,将
changetheStatic()
更改为static也会起作用。

您不能简单地调用这样的方法,因为在初始化类时会创建静态变量。这意味着即使没有类的实例,这些静态变量也将存在

因此,您只能通过将
changetheStatic()
方法更改为static来实现这一点

public static staticVar = changetheStatic();
public static String changetheStatic(){
    return "valueChanged";`
}

在访问修饰符
publicstaticstaticvar=changetheStatic()之后放置一个
static
==>您的代码不会编译,但是如果我想从另一个类访问静态变量而不声明为本地变量。您可以从任何地方访问它,只要它是公共的,想法是如果您想从instant方法访问它,您需要实例化一个对象并从那里调用该方法,否则,您需要将其从静态方法更改为静态方法