简体   繁体   English

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

[英]Change the public static variable by a non static method

I am implementing the same in a different context. 我在不同的背景下实现相同的功能。 I want to change the value of a static variable by calling non static Method as below, 我想通过调用非静态方法来更改静态变量的值,如下所示,

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

I am getting error like the "Change the method to static".. so any suggestions..?? 我收到错误,如“将方法更改为静态”..所以任何建议.. ??

This simply can't work. 这根本行不通。

You can only invoke non static methods on some instance . 您只能在某个实例上调用静态方法。 In your example, there is no instance; 在您的示例中,没有实例; thus the compiler would only allow you to call a static method. 因此编译器只允许您调用静态方法。

And just for the record: the naming is confusing. 而且只是为了记录:命名令人困惑。 You called your method changeTheStatic() . 你调用了你的方法changeTheStatic() But that method doesn't change anything . 但是这种方法并没有改变任何东西 It only returns a value. 它只返回一个值。 So you should be calling it something like getInitialValue() for example. 所以你应该像getInitialValue()那样调用它。

You can't do this. 你不能这样做。 You are trying to call an instance method without initializing an object. 您正在尝试在不初始化对象的情况下调用实例方法。 Instead what you can do is do this in you constructor 相反,你可以做的是在你的构造函数中执行此操作

          public class A {
           public static staticVar ;

           public A() {
                  A.staticVar = this.changetheStatic()
           }
           public String changetheStatic(){
             return "valueChanged";`
           }
         }

If you don't want to change it in the constructor, you can simply initialize an object and call the instance method 如果您不想在构造函数中更改它,则可以简单地初始化对象并调用实例方法

                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

The whole idea here is what you are doing is trying to call instant method as static, instant method needs to be called from an object 这里的整个想法就是你正在尝试将即时方法称为静态方法,需要从对象调用即时方法

         public static staticVar = changetheStatic();

so changing changetheStatic() to static would work too. 因此,将static changetheStatic()更改为静态也会起作用。

You can't simply call methods like this as static variables are created when the class is initialised. 您不能简单地调用这样的方法,因为在初始化类时会创建静态变量。 It means that these static variables will exist even if there's no instance of the class. 这意味着即使没有类的实例,这些静态变量也会存在。

Hence you can only do this by changing the changetheStatic() method to static 因此,您只能通过将changetheStatic()方法更改为static来实现此目的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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