Getting StackOverFlowError in Java

This is the program I am writing. I get a StackOverFlowError exception on startup:

 public class maininherit { maininherit h = new maininherit() { @Override public void mai() { System.out.print("inner"); } }; public static void main(String[] args){ maininherit t=new maininherit(); t.mai(); } public void mai(){ System.out.print("hellllll"); h.mai(); } } 

Here I get a StackOverFlowError only when I use the maininherit class as a reference in the inner class. If I use other classes, I do not get this error. Can someone clarify this to me?

Sorry that I am grateful for your answers, but I doubted that I did not know whether it is reasonable or not only to repeat the initializations only when I created an instance in the constructor of the same know.then class, how is it possible to have several initializations?

+4
source share
4 answers

This line:

 maininherit t=new maininherit(); 

Creates a new maininherit object (I will call it m0 ) that has a field of the same type (I will call it m1 )

When m0 is created, m1 is initialized. m1 also has a field, so m2 is initialized. m2 also has a field, so m3 is initialized, etc.

This would go on forever if the StackOverflowError didn't fumigate

+1
source

The implementation of your inner class simply overrides part of the maininherit class. So ... you initialize the maininherit class, then the variable h is initialized. The new statement was called, and then ... the inner class init maininherit again and it needs to set the variable h.

Your code is an infinitive initialization loop for the variable h.

+9
source

The problem here is not with your main and mai functions, but with the initialization of the member variable maininherit h . The problem is that each instance of maininherit creates a maininherit object (which, in turn, creates a maininherit object, etc.). A note that a single copy of all instances will be displayed as a member of static , which will solve this problem.

+1
source

A Stackoverflow error will occur whenever you try to create an instance of the same class as a member variable. Thus, the h instance is created endlessly, and therefore a stackoverflow error has occurred.

For example, the code you specified, even without an inner class, will throw a stackoverflow error

 public class maininherit { maininherit h=new maininherit(); public static void main(String[] args){ maininherit t=new maininherit(); t.mai(); } public void mai(){ System.out.print("hellllll"); h.mai(); }} 

Avoid creating an object of the class itself as a member or field

0
source

Source: https://habr.com/ru/post/1341270/


All Articles