开发者

Java, nested class: how to access 'higher' level variable?

i've this code

public class MasterClass {

    private String myVariable;
    private ValuesClass objectA;

        class ValuesClass {开发者_运维技巧

              public void method() {
                   myVariable = 1; // I can't access myVariable
              }
        }

} 

How to access myVariable from inside ValuesClass ?


What you are doing is exactly correct. Except that myVariable is a String, and you are trying to assign an int to it.

Now, if your inner class ALSO had a variable called myVariable, you would need some special syntax to access the one from the outer class:

MasterClass.this.myVariable = ...

Edit by Martijn: This is called a Qualified This.


You can access it directly with myVariable, or if you have conflicting variable names,

public class MasterClass {

private String myVariable;
private ValuesClass objectA;

    class ValuesClass {
          private String myVariable
          public void method() {
               MasterClass.this.myVariable = "Hello World!";
          }
    }

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜