本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
提问:为什么会报“不是一个封闭类”的错误?
我正在尝试制作俄罗斯方块游戏,但出现编译器错误
Shape is not an enclosing class
当我尝试创建对象时
public class Test {
public static void main(String[] args) {
Shape s = new Shapes.ZShape();
}
}
复制代码
我用内部类来声明每个形状,以下是我的代码的一部分:
public class Shapes {
class AShape {
}
class ZShape {
}
}
复制代码
我究竟做错了什么 ?
回答1:
ZShape 不是静态的,因此需要外部类的实例。
因此方案1:(没用Shape举例子,领会精神)
public class TestJue {
class Find{
void mm(){
System.out.println("call");
}
}
public static void main(String[] args) {
Find d = new TestJue().new Find();
d.mm();
}
}
复制代码
那么考虑前半句,改为静态,即有了方案二:
public class TestJue {
static class Find{
void mm(){
System.out.println("call");
}
}
public static void main(String[] args) {
Find d = new TestJue.Find();
d.mm();
}
}
复制代码
回答2:
我建议不要将非静态类转换为静态类,因为在这种情况下,您的内部类无法访问外部类的非静态成员。
方案三:
public class TestJue {
class Find{
void mm(){
System.out.println("call");
}
}
public static void main(String[] args) {
TestJue t = new TestJue();
TestJue.Find d = t.new Find();
d.mm();
}
}
复制代码
回答3:
从题干上来看,最好的还是用组合解决,很明显,Zshape和Sshape都可以通过shape类访问到。
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 = new Shape();
shape.zShape;
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END