How can I access a method that is inside a class that is inside another method of another class in Java

Below is a program that compiles successfully, but how do I access the m2 () method of class B, which is inside the m1 () method of class A.

class A{  
    public void m1()
    {
      System.out.println("A-m1"); 
        class B{
            public void m2()
            {
                System.out.println("B-m2");
            }
        }//end of class B
    }//end of m1() method
}// end of class A

      

+3


source to share


2 answers


It all depends on the scope. If you want to call m2()

at the end m1()

, it's as easy as creating a new instance B

and calling the method.

new B().m2()

      



If you want to call it outside of a method or before a declaration, it won't let you because of the scope.

If so, you should consider promoting your scope to the class level.

+3


source


Simple: you can't outside of the class (well, not smart).

B is the class local - it only exists within this method , so you can only instantiate this method. So in m1 () you can do simple and then call . But outside of this method, there is no syntax that allows you to "get" to . m1()

B b = new B()

b.m2()

A.m1().B.m2()

Well, you can also instantiate this method outside of this method using reflection. You see, the mangled class name is A $ 1B.class.



Therefore you can use Class.forName("A$1B")

to get the corresponding class; and when you have an instance of class A, you can use reflection again to create an object of that local class. And in that case, you could then call m2 () - again using reflection.

But: you shouldn't even try to do it. If this class B and its m2 () method need to be called from elsewhere, then just don't make it a local class. Make it an inner class or even a (not public) top level class.

+2


source







All Articles