Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inner class access to outer class method, same method names

I got a class and a innerclass

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?

like image 781
Grim Avatar asked Aug 27 '12 09:08

Grim


People also ask

Can inner class access outer class method?

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.

Can inner class access outer class variables?

Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.

Can an inner class be accessed from outside package?

Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.

Which modifier is applicable for both inner and outer classes?

Public Access Modifier in Java 1. Public access modifier can apply to instance variables, constructors, inner classes, outer class, methods but not with local variables.


1 Answers

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.

like image 194
Nandkumar Tekale Avatar answered Nov 05 '22 12:11

Nandkumar Tekale