2

我刚刚开始使用 Java,我需要一些帮助。我知道我不能对静态方法进行非静态引用,但我需要帮助来解决它。我正在阅读您可以通过创建对象的实例来访问非静态成员变量,但我不确定该怎么做。这是一些关于代码的。任何帮助或指示将不胜感激。

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

1 回答 1

3

您不能从静态方法引用非静态变量,因为该静态方法附加到类,而不是任何特定实例。从它的角度来看,那些非静态变量甚至都不存在。但是,您的问题具有误导性,因为无论如何您的代码中都没有显示任何非静态变量成员。您的问题似乎更像是如何实例化适当的分类规则并将其应用于静态方法参数。有很多方法可以做到这一点,最简单的方法是简单地实例化一个规则的实例:

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

但鉴于您有多个分类规则子类,您可能需要更复杂的方法来实例化它们。工厂在这里可能很有用,或者您可以使用一些更高级的对象创建模式,例如注入。

于 2012-04-08T03:23:14.273 回答