I am new to Java and OOPs and here is my issue. When I run the below code, I get the
Exception in thread \"main\" java.lang.StackOverflowError.
Your class JavaApplication1
has member JavaApplication1 ja
initialized in-place. This means that when you create new instance of JavaApplication1
in main()
method you call implicit default constructor that calls new JavaApplication1()
again, and again, and again.
If your want your code to work, first remove line
JavaApplication1 ja =new JavaApplication1();
I think you end up creating JavaApplication1 objects all the time which cause the stackOverflow exception. You should remove the line with the comment.
App2 a2 = new App2();
JavaApplication1 ja =new JavaApplication1(); //why do you need this?
public void run(){
Your class JavaApplication1
has field JavaApplication1 ja
which holds another instance of JavaApplication1
class, which also has its own ja
field which holds another instance of JavaApplication1
, and so on and on.
In other words, when you create instance of JavaApplication1
this instance creates its inner instance of JavaApplication1
and this inner instance creates another JavaApplication1
instance, which again creates instance JavaApplication1
... until stack will be full.
So when you run this code in your main method
JavaApplication1 ja1 = new JavaApplication1();
something like this happens
+-----------------------------------------------+
ja1 -> | JavaApplication1 instance |
+-----------------------------------------------+
| |
| +------------------------------------+ |
| ja -> | JavaApplication1 instance | |
| +------------------------------------+ |
| | | |
| | +-------------------------+ | |
| | ja -> |JavaApplication1 instance| | |
| | +-------------------------| | |
| | | | | |
| | | ja -> .... | | |
| | +-------------------------+ | |
| +------------------------------------+ |
+-----------------------------------------------+
Anyway I don't see where ja
field is ever used, so consider removing it from your code.
The problem is that you can't do something like this:
Class Try{
Try try = new Try();
public static void main(String[] arg)
{
Try try1 = new Try();
}
The issue with above code is that first the execution will start with your main method(ofcourse in this particular case :) ) then the try1 object will get created and all of the Class fields will get initialized, since you created an object of the same class you are in as a Class Field() it will try to re-initialize the Class fields, ending up in an infinite loop and inevitably the Famous STACK OVERFLOW error!
Now, talking in context of your question:
App2 a2 = new App2();
JavaApplication1 ja =new JavaApplication1(); //remove this line, it is causing the SO-error!!!