inner class access to outer class method, same method names

▼魔方 西西 提交于 2019-12-01 03:42:44
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.

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

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

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