【问题标题】:Non-static methods used in a static context error静态上下文错误中使用的非静态方法
【发布时间】:2012-11-03 19:30:18
【问题描述】:

我不断收到关于静态上下文中使用的非静态方法的这段代码的两个错误。此代码使用鸟、猫和狗的不同对象的 ArrayList,并使用名为 Pet 的接口将它们放入名为 petList 的 ArrayList。
我在第 4 行和第 6 行遇到相同的错误。

    public static void Feed(ArrayList petList){
        Scanner input = new Scanner(System.in);
        String petName = input.next();
        contains(petName, petList);

        if(ifThere == true){
            String feed = Pet.feed();
            System.out.println(petName + feed);
        }
        else{
            System.out.println("Unknown pet");
        }
    }


  public boolean contains (String petName, ArrayList petList){

    boolean ifThere = false;
    int sizeList = petList.size() -1;
    for(int i=0; sizeList > i; i++){
      Pet booleanPet = petList.get(i);
      String booleanName = booleanPet.getName();
      if (booleanName.equals(petName)){
        ifThere = true;
      }
}
return ifThere;

}

【问题讨论】:

  • 这表明 contains 和 feed 不是静态方法。如果没有更多代码,我们无法提供更多帮助。

标签: interface arraylist compiler-errors static-methods


【解决方案1】:

简而言之:不能从静态方法调用非静态方法。

解决方案: 1)将您的“包含”方法设为静态,它将解决问题。

或 2)(假设类的名称是 Pet 然后创建 Pet 类的实例并调用 contains 方法: 您的第 4 行可以替换为以下代码(C# 样式代码):

Pet somePet = new Pet ();
somePet.contains(petName, petList);

-- 额外细节: 静态方法是一种从不特定于任何对象的方法。例如添加2个数字。你 不需要实例化任何类来调用 Math.Add() 方法,因为 Add 是静态方法。

你也可以说 Static 是一种方法,它不是你肯定知道的虚拟含义 正在调用哪个方法。

【讨论】:

    猜你喜欢
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2014-05-03
    相关资源
    最近更新 更多