不是封闭的类Java

本文翻译自:Is not an enclosing class Java

I'm trying to make a Tetris game and I'm getting the compiler error 我正在尝试制作俄罗斯方块游戏,但出现编译器错误

Shape is not an enclosing class

when I try to create an object 当我尝试创建对象时

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

I'm using inner classes for each shape. 我为每个形状使用内部类。 Here's part of my code 这是我的代码的一部分

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

What am I doing wrong ? 我究竟做错了什么 ?


#1楼

参考:https://stackoom.com/question/1Myet/不是封闭的类Java


#2楼

ZShape is not static so it requires an instance of the outer class. ZShape不是静态的,因此它需要外部类的实例。

The simplest solution is to make ZShape and any nested class static if you can. 最简单的解决方案是,如果可以的话,使ZShape和任何嵌套的类static

I would also make any fields final or static final that you can as well. 我还可以使任何字段为finalstatic final


#3楼

I have encountered the same problem. 我遇到了同样的问题。 I solved by creating an instance for every inner public Class. 我通过为每个内部公共类创建一个实例来解决。 as for you situation, i suggest you use inheritance other than inner classes. 至于您的情况,我建议您使用继承而不是内部类。

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
}

then you can new Shape(); 然后可以新建Shape(); and visit ZShape through shape.zShape; 并通过shape.zShape访问ZShape;


#4楼

Suppose RetailerProfileModel is your Main class and RetailerPaymentModel is an inner class within it. 假设RetailerProfileModel是您的Main类,而RetailerPaymentModel是其中的内部类。 You can create an object of the Inner class outside the class as follows: 您可以在类外创建Inner类的对象,如下所示:

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

#5楼

No need to make the nested class as static but it must be public 无需将嵌套类设为静态,但它必须是公共的

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

#6楼

What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class. 我建议不要将非静态类转换为静态类,因为在这种情况下,您的内部类无法访问外部类的非静态成员。

Example : 范例:

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

So, in such case, you can do something like: 因此,在这种情况下,您可以执行以下操作:

Outer o = new Outer();
Outer.Inner obj = o.new Inner();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值