Is not an enclosing class Java

后端 未结 11 2416
轻奢々
轻奢々 2020-11-28 01:41

I\'m trying to make a Tetris game and I\'m getting the compiler error

Shape is not an enclosing class

when I try t

相关标签:
11条回答
  • One thing I didn't realize at first when reading the accepted answer was that making an inner class static is basically the same thing as moving it to its own separate class.

    Thus, when getting the error

    xxx is not an enclosing class

    You can solve it in either of the following ways:

    • Add the static keyword to the inner class, or
    • Move it out to its own separate class.
    0 讨论(0)
  • 2020-11-28 01:56

    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-28 02:01

    As stated in the docs:

    OuterClass.InnerClass innerObject = outerObject.new InnerClass();
    
    0 讨论(0)
  • 2020-11-28 02:02

    In case if Parent class is singleton use following way:

    Parent.Child childObject = (Parent.getInstance()).new Child();
    

    where getInstance() will return parent class singleton object.

    0 讨论(0)
  • 2020-11-28 02:08
    Shape shape = new Shape();
    Shape.ZShape zshape = shape.new ZShape();
    
    0 讨论(0)
  • 2020-11-28 02:08

    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(); and visit ZShape through shape.zShape;

    0 讨论(0)
提交回复
热议问题