我刚刚开始学习 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 );
}
您不能从静态方法引用非静态变量,因为该静态方法附加到类,而不是任何特定实例。从它的角度来看,那些非静态变量甚至不存在。但是,您的问题具有误导性,因为您的代码中没有任何地方显示任何非静态变量成员。您的问题似乎更多是如何实例化适当的分类规则并将其应用于静态方法参数。有多种方法可以做到这一点,最简单的是简单地实例化规则的实例:
ClassificationRule rule = new RuleFirstOccrnc();
rule.apply(userInput);
但考虑到您有多个分类规则子类,您可能需要一种更复杂的方法来实例化它们。工厂在这里可能很有用,或者您可以使用一些更高级的对象创建模式,例如注入。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)