• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About StackOverflowError

 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! Why my code cause StackOverflowError exception?

public class R extends Q{
String str="rStr";
static Q q=new R();
public static void main(String []str){
System.out.println(q.str);
}
}

class Q{
String str="qStr";
R r=new R();
}
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is such a tricky question and it had been discussed somewhere few months ago in this forum, and a very detailed answer by Kelvin Lim can be found.

click me

my own way to explain...

briefly, because from running the println statement in main(), it invokes call the q of type Q in the instance variable; class R inherits class Q, so it inherits variable("r") of type R in class Q.
THEN, variable("r") of type R goes through what class R offers to use, now back to the q of type Q AGAIN.

this runs and runs in a loop, until your pc blows up (not physically, mentally only)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic