2014-04-19 47 views
0

在java中说我们不能从静态方法调用非静态方法,这意味着什么?我们总是可以调用非静态方法frm静态方法使用对象虽然..'请说明java中的静态方法可以调用非静态方法

+0

编写代码。然后*搜索*的错误消息。你会发现许多重复像http://stackoverflow.com/questions/5201895/calling-the-instance-of-a-static-method?rq=1,http://stackoverflow.com/questions/18375971/can- i-call-instance-method-of-a-static-member-from-within-static-context?rq = 1(或this)可能重复[背后的原因是什么?非静态方法不能被引用静态上下文“?](http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static) – user2864740

回答

0

要调用非静态方法,您需要一个实例(对象) - 因为这些方法属于一个实例,并且通常只在实例的上下文中才有意义。

静态方法不属于一个实例 - 它们属于该类。因此,有没有必要先创建一个实例,你可以叫MyClass.doSomething()

void foo(){ 
    MyClass.doSomething(); 
} 

但是你可以从你提供的第一创建实例一个静态方法调用非静态方法。

static void bar(){ 
    MyObject o = new MyObject(); 
    o.doSomething(); 
} 
1

这里是一个很好的一段代码来说明这是什么意思:试图做的是报道不能做

class MyClass{ 

    static void func1(){ 
     func2(); //This will be an error 
    } 

    void func2(){ 
     System.out.println("Hello World!"); 
    } 

}