Is not an enclosing class Java

后端 未结 11 2418
轻奢々
轻奢々 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条回答
  • 2020-11-28 02:08

    To achieve the requirement from the question, we can put classes into interface:

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

    and then use as author tried before:

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

    If we looking for the proper "logical" solution, should be used fabric design pattern

    0 讨论(0)
  • 2020-11-28 02:10

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

    Sometimes, we need to create a new instance of an inner class that can't be static because it depends on some global variables of the parent class. In that situation, if you try to create the instance of an inner class that is not static, a not an enclosing class error is thrown.

    Taking the example of the question, what if ZShape can't be static because it need global variable of Shape class?

    How can you create new instance of ZShape? This is how:

    Add a getter in the parent class:

    public ZShape getNewZShape() {
        return new ZShape();
    }
    

    Access it like this:

    Shape ss = new Shape();
    ZShape s = ss.getNewZShape();
    
    0 讨论(0)
  • 2020-11-28 02:13

    Suppose RetailerProfileModel is your Main class and RetailerPaymentModel is an inner class within it. You can create an object of the Inner class outside the class as follows:

    RetailerProfileModel.RetailerPaymentModel paymentModel
            = new RetailerProfileModel().new RetailerPaymentModel();
    
    0 讨论(0)
  • 2020-11-28 02:18

    ZShape is not static so it requires an instance of the outer class.

    The simplest solution is to make ZShape and any nested class static if you can.

    I would also make any fields final or static final that you can as well.

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