How can I access this m1() method in the following program?

让人想犯罪 __ 提交于 2020-01-06 06:24:21

问题


How can i access the x = 15 value from m2() ? I am accessing following values as given in comment of the program.

  class A  {
        int x = 10;
        void m1(){
        int x = 15;     //How can we access x =15 ?

  class B{
        int x =20;
           void m2(){
            int x = 25;
            System.out.println(x);          //for x = 25
            System.out.println(this.x);     //for x = 20
            System.out.println(A.this.x);   //for x = 10
            System.out.println();           
            }
        }
    }
}

回答1:


Actually, you can't get access to x defined in m1(). To fix it, you could change the variable name: void m1() { int a = 15; ...}, or much better to use different names for all variables, because readability will be much higher (and at the first look, developer will not be hesitated what variable is used in every place):

public class A {
    private int a = 10;

    public void m1() {
        int m = 15;

        class B {
            private int b = 20;

            void m2() {
                int x = 25;
                System.out.println(x);  // x = 25
                System.out.println(a);  // a = 10
                System.out.println(b);  // b = 20
                System.out.println(m);  // m = 15
            }
        }
    }
}



回答2:


B is an inner class inside A. So, when you want to reference the outer class, use A.this, you want to use m1 from the outer class, so use A.this.m1()



来源:https://stackoverflow.com/questions/48801326/how-can-i-access-this-m1-method-in-the-following-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!