is not enclosing class java

November 2018

248k time

I’m trying to make a tetris game and I’m getting «Shape is not an enclosing class» when I try to create an object

I’m using inner classes for each shape. Here’s part of my code

What am I doing wrong ?

Содержание

  1. 13 answers
  2. Related Posts
  3. Check between two datetime if passed in Java/Andro >
  4. java.io.FileNotFoundException: /u/applic/wsadmin/geronimo217/geronimo8/var/catalina/work/TomcatWebContainer/SESSIONS.ser (Permis.
  5. Remove space between images added into a single pdf file with iText using java.
  6. 11 Answers 11

13 answers

Я столкнулся с той же проблемой. Я решена путем создания экземпляра для каждого внутреннего общественного класса. как и для вас ситуации, я предлагаю вам использовать наследование, кроме внутренних классов.

то вы можете новый Shape (); и посетить ZShape через shape.zShape;

Пусть RetailerProfileModel Ваш главный класс и RetailerPaymentModel является внутренним классом внутри него. Вы можете создать объект внутреннего класса вне класса следующим образом:

Одна вещь, которую я не понимаю, в первом чтении, когда принятый ответ был, что делает внутренний класс статический, в основном то же самое, перемещая его в свой собственный отдельный класс.

Таким образом, при получении ошибки

Вы можете решить в одном из следующих способов:

  • Добавьте static ключевое слово к внутреннему классу, или
  • Переместить его на свой собственный отдельный класс.

Я столкнулся с той же проблемой. Я решена путем создания экземпляра для каждого внутреннего общественного класса. как и для вас ситуации, я предлагаю вам использовать наследование, кроме внутренних классов.

то вы можете новый Shape (); и посетить ZShape через shape.zShape;

Иногда нам нужно создать новый экземпляр внутреннего класса , который не может быть статическим , поскольку это зависит от некоторых глобальных переменных родительского класса. В этой ситуации, если вы пытаетесь создать экземпляр внутреннего класса , который не является статическим, not an enclosing class выбрасывается ошибка.

Возьмем в качестве примера вопрос, что , если ZShape не может быть статическим , поскольку она нужна глобальная переменная Shape класса?

Как вы можете создать новый экземпляр ZShape ? Это как:

Добавить поглотитель в родительском классе:

I’m trying to make a tetris game and I’m getting “Shape is not an enclosing class” when I try to create an object

I’m using inner classes for each shape. Here’s part of my code

What am I doing wrong ?

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.

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:

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.

So, in such case, you can do something like:

No need to make the nested class as static but it must be public

In case if Parent class is singleton use following way:

where getInstance() will return parent class singleton object.

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.

then you can new Shape();
and visit ZShape through shape.zShape;

Check between two datetime if passed in Java/Andro >

Questions: I have two date time string, one is current time and second is given as follows. String currentTime = «05/30/2018 16:56:21»; String endTime = «05/30/2018 16:59:21»; Now I want to check if t.

java.io.FileNotFoundException: /u/applic/wsadmin/geronimo217/geronimo8/var/catalina/work/TomcatWebContainer/SESSIONS.ser (Permis.

Questions: I am facing ERROR [ManagerBase] IOException while saving persisted sessions: java.io.FileNotFoundException: /u/applic/wsadmin/geronimo217/geronimo8/var/catalina/work/TomcatWebContainer/SESS.

Remove space between images added into a single pdf file with iText using java.

Questions: I am trying to crate PDF files from a list of images. 4 image should cover a full page with no margin padding or anything. My problem is that the added images are separated by a white line.

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

I’m using inner classes for each shape. Here’s part of my code

What am I doing wrong ?

11 Answers 11

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.

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:

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.

So, in such case, you can do something like:

As stated in the docs:

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:

Access it like this:

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.

then you can new Shape(); and visit ZShape through shape.zShape;

No need to make the nested class as static but it must be public

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.

Источник: computermaker.info

Техника и Гаджеты
Добавить комментарий