【问题标题】:How to avoid the "non-static method referenced from a static context" in java ? really simple如何避免java中的“从静态上下文引用的非静态方法”?真的很简单
【发布时间】:2012-11-19 03:43:21
【问题描述】:

当我尝试构建这个程序时,总是出现类似“从静态上下文引用的非静态方法”的错误 我认为这是因为我可以在“main”中使用“addto”功能。那么我该如何解决这个问题呢?我需要一个公共数组列表,因为我必须在“addto”中进行计算

谢谢!

public class Calculation {  
    ArrayList<int[]> cal = new ArrayList<>();

    public static void main(String[] args) {
    System.out.println(addto(3,5));
    }

    String addto(int figone, int figtwo){
     ........do the calculations by using arraylist cal
    }
 }

【问题讨论】:

  • 你需要一个Calculation的实例来调用非静态方法addto

标签: java static


【解决方案1】:

您需要在主函数中实例化一个 Calculation 对象才能使用 Calculation 的非静态方法。

非静态方法仅作为对象的成员“存在”(您可以将其视为类的实例)。为了完成这项工作,您需要编写:

System.out.println(new Calculation().addto(3, 5))

【讨论】:

    【解决方案2】:

    真的很简单吗?

    System.out.println(new Calculation().addto(3,5));
    

    Calculation calculation = new Calculation();
    System.out.println(calculation.addto(3,5));
    // and use 'calculation' some more ...
    

    (您也可以在addto 方法声明中添加static 修饰符,但是您还需要将cal 设为静态,以便addto 可以使用它。坏主意。)


    好的。所以编译方法实际上是在说 addto 被声明为实例方法......但是你试图调用它而不说 which 使用实例。实际上,您正在尝试将其作为静态方法来调用。

    “修复”(见上文)是创建一个实例并在其上调用方法。

    【讨论】:

    • 是的:System.out.println(new Calculation().addto(3,5));。没有:or add a static modifier to the addto method declaration。除非您将“cal”设为静态。你的第一个建议是最好的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2017-07-01
    • 2016-03-02
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    相关资源
    最近更新 更多