aspose file tools*
The moose likes Java in General and the fly likes Problem With 'static' When Running Stand Alone Java Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem With Watch "Problem With New topic
Author

Problem With 'static' When Running Stand Alone Java Class

JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
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

Joined: Aug 16, 2005
Posts: 13884
    
  10

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:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
Thanks very much for pointing out the direction.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem With 'static' When Running Stand Alone Java Class
 
Similar Threads
MasterExam LAb Question (modified)
Reading strings from a line problem _ any help!!
Graphs and identifying adjacent nodes
Adding Array to a List - Cannot Resoleve the Problem for a Week
JSTL tag library import problem