-1

The simple code below generates an error:

non-static variable this cannot be referenced from a static context

What does this error mean? Ok I understand that this is a wrong syntax for instantiating the inner class objects.But I am not clear how I am "referencing non static variable this from a static context" by doing so."

public class Test{
    class Test1{}
    public static void main(String[] args) {
    // generates an error
    new Test1(); 
    }
}

does new Test1() in above code means this.new Test1();

hermit
  • 1,048
  • 1
  • 6
  • 16

3 Answers3

2

If the application requirements allow you to make the class Test1 a static class, then do this.

public class Test {

    static class Test1 {
    }

    public static void main(String[] args) {
        new Test.Test1();
    }
}

If the class Test1 needs to be non-static, then do this.

public class Test {

    class Test1 {
    }

    public static void main(String[] args) {
        new Test().new Test1();
    }
}

Notice the syntax of the instantiation in both the cases.

Shrinivas Shukla
  • 4,325
  • 2
  • 21
  • 33
  • If i simply do new Test1() as in my question then is it equivalent to this.newTest1() ? – hermit Jul 09 '15 at 07:37
  • FIrst point..... You cannot access `this` in `main()` beacause `this` is non-static and you **CANNOT** access non-static member from any static method. Second point...... if `class Test1` is `static`, then you can access it directly from `main()`.. In this case, `new Test.Test1()` and `new Test1()` is same. – Shrinivas Shukla Jul 09 '15 at 10:50
0

You can see below code:

public class Test {

static class Test1 {
}

public static void main(String[] args) {

    Test.Test1 obj = new Test.Test1();
}}
Rafiq
  • 740
  • 1
  • 5
  • 17
0

You have to have a reference to the outer class Test as well.

Test1 inner = new Test().new Test1();

If inner Test1 was static then it would be

 Test1 inner = Test.new Test1();
AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23