【问题标题】:How to change static variable inside in a class by a method如何通过方法更改类中的静态变量
【发布时间】:2019-04-01 01:14:55
【问题描述】:

我有三个班级:

一级

public class One {
   private static Two object;

   public static void set_up(Two object) {
       int y = object.get();
       System.out.println(y);
   }

   public static void prn () {
       System.out.println(object.get());
   }

}  

二班

public class Two {
   private int x;


   public int get() {
       return x;
   }

   Two(int n){
       x = n;
   }
 }

三班

public class Three {
   public static void main( String[] argv ) {
       One st = new One();
       Two two = new Two(2);

       st.set_up(two);

       st.prn();
   }
}

我想将Two 类中的静态变量object 更改为method set_up(Two object)。 问题是类中的静态变量与方法中的参数具有相同的名称。如何修改 set_up(Two object) 以便将给定参数中的值复制到静态对象?

【问题讨论】:

  • One.object = object.
  • @MWB 这个?在静态方法里面?我不这么认为。
  • 线程“main”java.lang.Error 中的异常:未解决的编译问题:不能在 Three.main(Three.java) 的 One.set_up(One.java:6) 的静态上下文中使用它:6)
  • 我不能在静态方法@Zephyr 中真正使用“this”
  • @NoName 错过了;你是对的。

标签: java methods static static-methods static-variables


【解决方案1】:

你可以使用类名来限定它:

public static void set_up(Two object) {
    One.object = object;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多