我试图做一个俄罗斯方块游戏,我得到了编译器错误

Shape不是一个外围类

当我尝试创建一个对象时

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

我为每个形状使用内部类。这是我的部分代码

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

我做错了什么?


当前回答

Shape shape = new Shape();
Shape.ZShape zshape = shape.new ZShape();

其他回答

如文件所述:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

为了达到问题的要求,我们可以把类放到接口中:

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

然后使用作者之前尝试过的方法:

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

如果我们寻找合适的“逻辑”解决方案,应该采用面料图案设计

假设RetailerProfileModel是Main类,RetailerPaymentModel是Main类中的一个内部类。你可以在类外部创建一个Inner类的对象,如下所示:

RetailerProfileModel.RetailerPaymentModel paymentModel
        = new RetailerProfileModel().new RetailerPaymentModel();

我也遇到过同样的问题。 我通过为每个内部公共类创建一个实例来解决这个问题。 至于你的情况,我建议你使用继承而不是内部类。

public class Shape {

    private String shape;

    public ZShape zShpae;
    public SShape sShape;

    public Shape(){
      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
}

然后你可以新建Shape(); 通过shape.zShape访问ZShape;

在阅读公认的答案时,我一开始没有意识到的一件事是,使内部类静态基本上与将它移动到它自己的单独类是一样的。

因此,当得到错误时

XXX不是一个外围类

你可以用以下两种方法来解决:

将static关键字添加到内部类或 将它移到单独的类中。