Win a copy of Learning Java by Building Android Games this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Problem With 'static' When Running Stand Alone Java Class  RSS feed

 
Ranch Hand
Posts: 1309
  • 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:
 
Java Cowboy
Sheriff
Posts: 16084
88
Android IntelliJ IDE Java Scala Spring
  • 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
  • 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
Boost this thread!