Accessing non-static member variables from static methods

霸气de小男生 提交于 2019-12-24 00:56:29

问题


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 );
    }

回答1:


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.



来源:https://stackoverflow.com/questions/10060109/accessing-non-static-member-variables-from-static-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!