inner class access to outer class method, same method names

柔情痞子 提交于 2019-12-01 00:47:53

问题


i got a class and a subclass

01 public class A{
02   void test(){};
03   public class B{
04     void test(){
05       test();
06     }
07   }
08 }

Ok, in line 05 id like to access the method test of class A. But i go into a loop because i dont know how to specify to use the method of class A.

Any ideas?


回答1:


01 public class A{
02   void test(){};
03   public class B{
04     void test(){
05       test();  // local B.test() method, so recursion, use A.this.test();
06     }
07   }
08 }

EDIT : As @Thilo mentioned : Avoid using same method names in outer class and inner class, this will avoid naming conflicts.




回答2:


You can do something like that :

public class A{
   void test(){
        System.out.println("Test from A");
    };
    public class B{
        void test(){
            System.out.println("Test from B");
            A.this.test();
        }
    }

    public static void main(String[] args) {
            A a = new A();
            B b = a.new B();
            b.test();
    }
}

You then have the following output :

Test from B
Test from A



回答3:


Class B doesn't has to be a so- called nested class to extend Class A just write

public class B extends A {
...

}

than you can call A's test() like

super.test()

If you call test() like you do it that's what we call recursive and will freeze until the Day of Judgement




回答4:


If you make it static you can call

A.test()

Else you need an instance of A to use in B

A a;
a.test();


来源:https://stackoverflow.com/questions/12139160/inner-class-access-to-outer-class-method-same-method-names

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