• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem With 'static' When Running Stand Alone Java Class

 
JiaPei Jen
Ranch Hand
Posts: 1309
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a Java class that recursively builds a 'tree' . This Java class works as I expected without problem. I am able to write out this 'tree" to the console "line by line" with proper indentation.

The problem occurs when I try to iterate through this 'tree' in the public static void main(String[] arg) method -- Each line in the tree is an Array. And I have to declare this Array (called titleArray in my code) non-static; otherwise, I end up with picking up the very last line of my hard-coded data.

Besides, I also have to declare the List (called recursiveTextArray in my code) non-static; otherwise, I end up with picking up the first Array that I ever build and run into endless iterations till the heap size is exhausted. Note that each element of that List is an Array object.

Then, this non-static Array and this non-static List cannot be accessed in the public static void main(String[] arg) method.

What should I do?

Here is my code that works without problem (the one I do not access the 'titleArray' in the main(String[] arg) method):

And the code below gives me the static and non-static problem:
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the lines that you have marked with "compilation error" you are trying to access non-static member variables, but you are not specifying at which object you are looking.

Remember that non-static methods always execute in the context of a current object. Static methods are class-level methods; they do not execute on a specific object. You cannot access non-static members from a static method, because there is no current object at which you're looking.

You should specify the object that you want to look at explicitly, for example:
 
JiaPei Jen
Ranch Hand
Posts: 1309
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much for pointing out the direction.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic