Ashutosh Ashutosh - 2 months ago 19
Java Question

How to call outer Class method from Inner Class?

I want to call a outer class method from non-static inner class in Java.

public class A {

public void aMethod(int i){
System.out.println(i);
}

public class B{

public void bMethod(){
System.out.println("This method belongs to Inner Class");
}
}


I want to call aMethod from Class B. As instance of non static Inner class contains instance of outer class, I tried by calling
aMethod(3)
from inner class, but this is not working. Please help.

Answer

It is working perfectly. Why Exactly it will not work.

An example showing calling of this method is working.

 class A {

public void aMethod(int i){
    System.out.println(i);
}

public class B{

    public void bMethod(){
        aMethod(3);
        System.out.println("This method belongs to Inner Class");
    }
       }
}
public class C {
    public static void main(String[] args) {
        A.B innerObject = new A().new B();
        innerObject.bMethod();
    }
}