-3

I got an error when I try to create new class (that defined in the parent class) from a static method (in the parent class).

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

public class ParentClass {
    public class ChildClass {
        ...
    }

    public void method () {
        // Compiles
        ChildClass childClass = new ChildClass();
    }

    public static void static_method () {
        // error: non-static variable this cannot be referenced from a static context
        ChildClass childClass = new ChildClass();
    }
}

Of course I can creat the ChildClass class as new individual class but I couldn't understand why this wouldn't work.

------- Edit -------

Making the inner class (ChildClass) static would make the class work as separate class (source), as it was in different class, which is exactly what I needed.

    public static class ChildClass {

------- Edit #2 -------

Just to make it clear non-static class, as in the first code example, when used and created from non-static method like in method(), can access and use the ParentClass's functions and vriables.

Mr Me
  • 3
  • 4
  • 3
    An inner class needs a reference to the outer containing class; make it `static`. Change `public class ChildClass` to `public static class ChildClass` - or you'll need an instance of `ParentClass`. – Elliott Frisch May 10 '18 at 22:10
  • @ElliottFrisch If you convert your comment to an answer (and ping me), I promise an upvote. – Dawood ibn Kareem May 10 '18 at 22:11
  • @Elliott Frisch Thanks for your answer - it works perfect.My problem was in my prejudice of what static class mean. Thanks. – Mr Me May 11 '18 at 09:37

1 Answers1

0

Child class is not a static class, thus can not be used in static members. To be able to use it in static members make it static:

public static class ChildClass {
        ...
}
Rad
  • 4,292
  • 8
  • 33
  • 71