【问题标题】:Referencing non-static variable from a static context从静态上下文引用非静态变量
【发布时间】:2014-09-26 14:32:48
【问题描述】:

我正在阅读 Kathy 和 Bert SCJP 1.6 并遇到以下代码:

class Bar {
int barNum = 28;
}

class Foo {
  Bar myBar = new Bar();
  void changeIt(Bar myBar) {
    myBar.barNum = 99;
    System.out.println("myBar.barNum in changeIt is " + myBar.barNum);
    myBar = new Bar();
    myBar.barNum = 420;
    System.out.println("myBar.barNum in changeIt is now " + myBar.barNum);
 }
  public static void main (String [] args) {
    Foo f = new Foo();
    System.out.println("f.myBar.barNum is " + f.myBar.barNum);
    f.changeIt(f.myBar);
    System.out.println("f.myBar.barNum after changeIt is "
    + f.myBar.barNum);
 }
}

虽然是在阴影变量的主题下,但我无法理解如何在 main() 方法(静态)中引用非静态变量 myBar?

【问题讨论】:

标签: java static non-static


【解决方案1】:

诀窍在于myBar 访问的上下文不是静态的。

通过编写f.myBar 而不仅仅是简单的myBar,您可以在存储在f(一个局部变量)中的实例的上下文中访问它。

这是启动应用程序常用模式的基础。

public class Main {
   private final Foo param1;
   private final Bar param2;       


   private Main( Foo initParam1, Bar initParam2 ) {
      //initialise the fields 
   }

   private void run() {
      // execute the application
   }

   public static void main( String [] args ) {
      // parse the command line arguments
      Foo parsedParam1 = ...
      Bar parsedParam2 = ...
      Main main = new Main( parsedParam1, parsedParam2 );
      main.run();
   }
}

【讨论】:

    【解决方案2】:

    static Java 中的变量属于Class,并且它的值对于该类的所有实例都保持相同static 变量在类加载到 JVM 时初始化

    另一方面,实例变量对于每个实例都有不同的值。它们是在使用new 运算符或使用像Class.newInstance() 这样的反射创建对象实例时创建的。所以在你的情况下:

    /* this is valid since compiler knows myBar
    belongs to an instance of Foo called f */
    Foo f = new Foo();
    f.changeIt(f.myBar);  
    
    /* This is invalid because compiler doesn't know which
    myBar this is since it isn't connected to a class */
    Foo f = new Foo();
    f.changeIt(myBar); 
    

    因此,如果您尝试在没有任何实例的情况下访问非静态变量,编译器会给您一个错误,因为这些变量尚未创建,因此不存在。

    【讨论】:

    • 非常感谢您用简单的语言表达。我在试图弄清楚它时遇到了很多麻烦。
    猜你喜欢
    • 2014-12-25
    • 2019-03-17
    • 2011-11-30
    • 1970-01-01
    相关资源
    最近更新 更多