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

Shape不是一个外围类

当我尝试创建一个对象时

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

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

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

我做错了什么?


当前回答

如果有人有这个问题,试图实例化第三方组件。

在我的情况下,我使用这个组件进行单元测试:ChannelSftp。LsEntry

做通常的实例化给我的问题:

解决方案是:

    ChannelSftp channelSftp =  new ChannelSftp();
    Constructor<ChannelSftp.LsEntry> constructor = (Constructor<ChannelSftp.LsEntry>) ChannelSftp.LsEntry.class.getDeclaredConstructors()[0];
    constructor.setAccessible(true);
    ChannelSftp.LsEntry lsEntry = constructor.newInstance(channelSftp, "file1.txt", null);

我在这里找到了原始代码

其他回答

如果有人有这个问题,试图实例化第三方组件。

在我的情况下,我使用这个组件进行单元测试:ChannelSftp。LsEntry

做通常的实例化给我的问题:

解决方案是:

    ChannelSftp channelSftp =  new ChannelSftp();
    Constructor<ChannelSftp.LsEntry> constructor = (Constructor<ChannelSftp.LsEntry>) ChannelSftp.LsEntry.class.getDeclaredConstructors()[0];
    constructor.setAccessible(true);
    ChannelSftp.LsEntry lsEntry = constructor.newInstance(channelSftp, "file1.txt", null);

我在这里找到了原始代码

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

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

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

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

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

如文件所述:

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

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

因此,当得到错误时

XXX不是一个外围类

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

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

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