V Sebi V Sebi - 2 months ago 12
Java Question

Is not an enclosing class Java

I'm trying to make a tetris game and I'm getting "Shape is not an enclosing class" when I try to create an object

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


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

public class Shape {

private String shape;
private int[][] coords;
private int[][] noShapeCoords = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
private int[][] zShapeCoords = { { 0, -1 }, { 0, 0 }, { -1, 0 }, { -1, 1 } };
private int[][] sShapeCoords = { { 0, -1 }, { 0, 0 }, { 1, 0 }, { 1, 1 } };
private int[][] lineShapeCoords = { { 0, -1 }, { 0, 0 }, { 0, 1 }, { 0, 2 } };
private int[][] tShapeCoords = { { -1, 0 }, { 0, 0 }, { 1, 0 }, { 0, 1 } };
private int[][] squareShapeCoords = { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } };
private int[][] lShapeCoords = { { -1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } };
private int[][] mirroredLShapeCoords = { { 1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } };

public Shape(){
int[][] coords = noShapeCoords;
shape = "NoShape";
}

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

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

//etc
}


What am I doing wrong ?

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.