Is not an enclosing class Java

后端 未结 11 2532
轻奢々
轻奢々 2020-11-28 01:41

I\'m trying to make a Tetris game and I\'m getting the compiler error

Shape is not an enclosing class

when I try t

11条回答
  •  温柔的废话
    2020-11-28 02:10

    Sometimes, we need to create a new instance of an inner class that can't be static because it depends on some global variables of the parent class. In that situation, if you try to create the instance of an inner class that is not static, a not an enclosing class error is thrown.

    Taking the example of the question, what if ZShape can't be static because it need global variable of Shape class?

    How can you create new instance of ZShape? This is how:

    Add a getter in the parent class:

    public ZShape getNewZShape() {
        return new ZShape();
    }
    

    Access it like this:

    Shape ss = new Shape();
    ZShape s = ss.getNewZShape();
    

提交回复
热议问题