This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: why is the error “not a closed class” reported?

I am trying to make a Tetris game, but there is a compiler error

Shape is not an enclosing class

When I try to create objects

public class Test {
    public static void main(String[] args) {
        Shape s = newShapes.ZShape(); }}Copy the code

I declare each shape with an inner class. Here’s part of my code:

public class Shapes {
    class AShape {}class ZShape {}}Copy the code

What did I do wrong?

Answer 1:

ZShape is not static, so you need an instance of an external class.

Therefore, plan 1 :(use Shape as an example to understand the spirit)

public class TestJue {
    class Find{
        void mm(a){
            System.out.println("call"); }}public static void main(String[] args) {
        Find d = new TestJue().new Find(a); d.mm(); }}Copy the code

So consider the first half of the sentence, change to static, that is, plan 2:

public class TestJue {
    static class Find{
        void mm(a){
            System.out.println("call"); }}public static void main(String[] args) {
        Find d = newTestJue.Find(); d.mm(); }}Copy the code

Answer 2:

I recommend not converting a non-static class to a static class, because in that case, your inner class cannot access the non-static members of the outer class.

Solution 3:

public class TestJue {
    class Find{
        void mm(a){
            System.out.println("call"); }}public static void main(String[] args) {
        TestJue t = new TestJue();
        TestJue.Find d = t.new Find(a); d.mm(); }}Copy the code

Answer 3:

Both Zshape and Sshape can be accessed through shape.

public class Shape {

    private String shape;

    public ZShape zShpae;
    public SShape sShape;

    public Shape(a){
      int[][] coords =  noShapeCoords;
      shape = "NoShape";
      zShape = new ZShape();
      sShape = new SShape();
    }

    class ZShape{
      int[][] coords =  zShapeCoords;
      String shape = "ZShape";
    }

    class SShape{
      int[][] coords = sShapeCoords;
      String shape = "SShape";
    }

 //etc
 // Access methods
 Shape shape = new Shape();
 shape.zShape;
}
Copy the code