2

I have an inner class, which I want to instantiate from the static method of the parent class as follows:

public class MyClass {
    public class B {
        private int v;
        B(int x) {
            v = x;
        }

        public void pr() {
            System.out.println(this.v);
        }
    }

    public static void main(String args[]) {
      int x=10;
      int y=25;
      int z=x+y;
    B bb = new B(3);
      System.out.println("Sum of x+y = " + z);
    }
}

It is throwing an error as follows:

error: non-static variable this cannot be referenced from a static context
    B bb = new B(3);
           ^
1 error
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
user3243499
  • 2,953
  • 6
  • 33
  • 75
  • 1
    Your inner class should be a static nested class, not an inner class. Instantiating an inner class needs an instance of the outer class, but you don't have any, and B doesn't need any. – JB Nizet Dec 13 '19 at 17:50
  • 1
    It is a non static inner class. So you have to create it through an instance of the parent. `MyClass a = new MyClass();` and then `B b = a.new B();`. You most likely did not intend to have a non-static inner class, I suppose. Using a non static inner class like that is rarely appropriate. Their use case is mostly if an instance of outer needs some utility instances, such as a list might need an iterator. – Zabuzard Dec 13 '19 at 17:51
  • new MyClass().new B(); – Vishrant Dec 13 '19 at 17:54

0 Answers0