问题

这个问题在这里已有答案:

  • 无法对非静态方法进行静态引用8个答案

当我尝试在静态类中调用非静态方法时,我收到错误。

无法从类型回放中对非静态方法methodName()进行静态引用

我不能使方法静态,因为这也给我一个错误。

此静态方法无法从xInterface隐藏实例方法

有没有办法在另一个静态方法中调用非静态方法? (这两种方法分开包和单独的类)。


#1 热门回答(115 赞)

从静态方法调用非静态方法的唯一方法是让类的实例包含非静态方法。根据定义,非静态方法是在某个类的实例上调用ON的方法,而静态方法属于类本身。


#2 热门回答(78 赞)

你可以创建要在其上调用方法的类的实例,例如

new Foo().nonStaticMethod();

#3 热门回答(32 赞)

首先创建一个类Instance并使用该实例调用非静态方法。例如,

class demo {

    public static void main(String args[]) {
        demo d = new demo();
        d.add(10,20);     // to call the non-static method
    }

    public void add(int x ,int y) {
        int a = x;
        int b = y;
        int c = a + b;
        System.out.println("addition" + c);
    }
}

原文链接