局部和全局变量(Java)[重复]

时间:2021-09-08 16:46:38

This question already has an answer here:

这个问题在这里已有答案:

I have the class X and a variable called x In my inner class Y I have a variable called y

我有类X和一个名为x的变量在我的内部类Y中我有一个名为y的变量

I want: x = y

我想:x = y

I made a Getter Method for Y and for X but the error accurs: non-static method 'getY()' cannot be referenced from a static context.

我为Y和X做了一个Getter方法,但是错误准确:非静态方法'getY()'不能从静态上下文中引用。

I haven't set the getX() static nor final. I have tried it both ways as well but it's not working.

我没有设置getX()静态也没有设置final。我也尝试了两种方式,但它不起作用。

EDIT:

public class X {
    Variable v = new Variable();
    [... here is something done with v]

    class Y {
      Variable v_new = v;
      [works with v]

    }

    v = v_new; // ???
}

1 个解决方案

#1


1  

Your inner class Y can access class X's variable v, so no need to redeclare it as variable v_new...
If you must, then use a public getter method, and reference it through an instance of Y.

你的内部类Y可以访问类X的变量v,所以不需要将它重新声明为变量v_new ...如果必须,则使用公共getter方法,并通过Y的实例引用它。

Something like this:

像这样的东西:

public class X {
  Variable v = new Variable();
  [... here is something done with v]

  class Y { 
    Variable v_new = v;
    [works with v]
    public Variable getV() { return v_new; }
  }

  Y y = new Y();
  v = y.getV();
} 

#1


1  

Your inner class Y can access class X's variable v, so no need to redeclare it as variable v_new...
If you must, then use a public getter method, and reference it through an instance of Y.

你的内部类Y可以访问类X的变量v,所以不需要将它重新声明为变量v_new ...如果必须,则使用公共getter方法,并通过Y的实例引用它。

Something like this:

像这样的东西:

public class X {
  Variable v = new Variable();
  [... here is something done with v]

  class Y { 
    Variable v_new = v;
    [works with v]
    public Variable getV() { return v_new; }
  }

  Y y = new Y();
  v = y.getV();
}