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

Shape不是一个外围类

当我尝试创建一个对象时

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

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

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

我做错了什么?


当前回答

我的建议是不要将非静态类转换为静态类,因为在这种情况下,内部类无法访问外部类的非静态成员。

例子:

class Outer
{
    class Inner
    {
        //...
    }
}

所以,在这种情况下,你可以这样做:

Outer o = new Outer();
Outer.Inner obj = o.new Inner();

其他回答

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

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

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

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

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

public class Test {
    public static void main(String[] args) {
        Shape s = new Shapes.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);

我在这里找到了原始代码

如文件所述:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Shape shape = new Shape();
Shape.ZShape zshape = shape.new ZShape();