Accessing non-static member variables from static methods

tom3322 picture tom3322 · Apr 8, 2012 · Viewed 16k times · Source

I'm just starting on Java and I need some help. I know I cannot make a non-static reference on a static method but I need help trying to work around it. I was reading you can access non-static member variables, by creating an instance of the object but I'm not sure exactly how to do it. Here is some on the code. Any help or directions would be reallya appreciated.

package tweetClassification;        

public class PriorityRules {    

    public static void prioritize( final String userInput ){

            ClassificationRule.apply( aUserInput ); //ERROR
                            // Cannot make a static reference to 
                            // the non-static method apply(String)
                            // from the type ClassificationRule
        }
} 

*----------------------------------------------------------------
package tweetClassification;

public class ClassificationRule {

        public void apply (final String aUserInput) {   

            apply( aUserInput );
        }
    }

*----------------------------------------------------------------
package tweetClassification;

import java.util.ArrayList;

public class RuleFirstOccrnc extends ClassificationRule {

    public void apply ( final String aUserInput ){

        for( TweetCat t: TwtClassif.tCat )
            applyFirstOccurrenceRuleTo( t, aUserInput );
    }

*----------------------------------------------------------------
package tweetClassification;

public class RuleOccrncCount extends ClassificationRule {

    public void apply ( final String aUserInput ){

        for( TweetCat t: TwtClassif.tCat )
            applyOccurrenceCountRuleTo( t, aUserInput );
    }

Answer

Perception picture Perception · Apr 8, 2012

You can't refer to non-static variables from a static method because that static method is attached to the class, as opposed to any particular instance. From its point of view, those non-static variables don't even exist. However, your question is misleading because nowhere in your code do you show any non-static variable members anyway. It would seem your question is more along the lines of how to instantiate an appropriate classification rule and apply it to the static method argument. There are a number of ways to do this, the simplest would be to simply instantiate an instance of a rule:

ClassificationRule rule = new RuleFirstOccrnc();
rule.apply(userInput);

But given that you have multiple sub-classes of classification rule, you probably need a more sophisticated method of instantiating them. A factory could be useful here, or you can use some more advanced object creation patterns like Injection.