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

Shape不是一个外围类

当我尝试创建一个对象时

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

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

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

我做错了什么?


当前回答

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

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;

其他回答

如文件所述:

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

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

例子:

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

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

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

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

在我的情况下,我使用这个组件进行单元测试: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 class Test {
    public static void main(String[] args) {
        Shape shape = new Shape();
        Shape s = shape.new Shape.ZShape();
    }
}

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

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