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

Shape不是一个外围类

当我尝试创建一个对象时

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

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

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

我做错了什么?


当前回答

如文件所述:

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

其他回答

如果父类是单例的,使用以下方法:

Parent.Child childObject = (Parent.getInstance()).new Child();

其中getInstance()将返回父类单例对象。

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

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();
Shape shape = new Shape();
Shape.ZShape zshape = shape.new ZShape();

ZShape不是静态的,所以它需要一个外部类的实例。

最简单的解决方案是使ZShape和任何嵌套类都是静态的。

我也会将任何字段设置为final或static final。