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
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
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();
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();
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();
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.