Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 769
V Sebi Avatar asked Nov 27 '13 20:11

V Sebi


People also ask

What is an enclosing class in Java?

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Is not an enclosing class activity?

not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor. Show activity on this post.

How do you create an inner class in Java?

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.


3 Answers

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.

like image 182
Peter Lawrey Avatar answered Oct 19 '22 00:10

Peter Lawrey


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();
like image 32
Vishal Kumar Avatar answered Oct 19 '22 01:10

Vishal Kumar


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();
like image 55
Amit Upadhyay Avatar answered Oct 19 '22 02:10

Amit Upadhyay