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

Shape不是一个外围类

当我尝试创建一个对象时

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

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

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

我做错了什么?


当前回答

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

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

其他回答

不需要将嵌套类设置为静态的,但它必须是公共的

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

如文件所述:

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

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

因此,当得到错误时

XXX不是一个外围类

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

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

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

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

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