问题
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