You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何移除static关键字后div方法无法调用?静态上下文报错解析

解答:Java中static与非static方法的调用规则

1. 为何没有static关键字我就无法使用该方法?

在Java里,方法分两种核心类型:static(静态)方法和非static(实例)方法,它们的调用逻辑完全不同:

  • static方法属于整个类本身,不需要创建类的对象就能直接调用,是类级别的公共资源;
  • 非static方法属于类的具体实例对象,必须先通过new关键字创建类的实例,才能通过这个实例对象去调用方法。

你的程序入口main方法是static的——这是Java的硬性规定,程序启动时会直接调用类的static main方法。在这个static上下文里,你没有创建Program类的实例对象,直接调用非static的div方法时,Java根本不知道你要调用哪个对象的div方法,自然会报错阻止你。

2. 为何div方法移除static关键字后无法正常运行?

当你把div的static修饰符去掉后,它就变成了实例方法。而main方法是static的,在static环境下直接调用实例方法,就会触发你看到的错误:

\Playground:13: error: non-static method div(int, int) cannot be referenced from a static context
System.out.println(div(42, 0));

这个错误的本质是:static方法不依赖任何实例对象,它属于类;而实例方法必须依附于某个具体的对象才能存在。在static的main方法里,没有现成的Program实例可以绑定div方法,Java不允许这种“无对象依附”的调用。

如果想移除static后让代码正常运行,你需要先创建Program的实例,再通过实例调用方法,修改后的代码如下:

public class Program {
    int div(int a, int b) throws ArithmeticException {
        if(b == 0) {
            throw new ArithmeticException("Division by Zero");
        } else {
            return a / b;
        }
    }

    public static void main(String[] args) {
        // 创建Program类的实例对象
        Program program = new Program();
        // 通过实例对象调用非static方法
        System.out.println(program.div(42, 2));
    }
}

简单总结:static方法可以直接在static上下文(比如main)里调用;非static方法必须先创建类的实例,通过实例对象来调用。

内容的提问来源于stack exchange,提问作者Mutabar Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:23:45