Java – ‘Is Not an Enclosing Class’ Error Explained

inner-classesjava

I'm trying to make a Tetris game and I'm getting the compiler error when I try to create an object

Shape is not an enclosing class

public class Test {
    public static void main(String[] args) {
        Shape s = new Shapes.ZShape();
    }
}

I'm using inner classes for each shape. Here's part of my code

public class Shapes {
    class AShape {
    }
    class ZShape {
    }
}

What am I doing wrong?

Best Answer

ZShape is not static so it requires an instance of the outer class.

The simplest solution is to make ZShape and any nested class static if you can.

I would also make any fields final or static final that you can as well.

Related Question