简体   繁体   English

Java中的静态方法可以调用非静态方法

[英]Static method in java can call non static method

有人说在Java中我们不能从静态方法中调用非静态方法。这到底意味着什么?我们总是可以使用对象调用非静态方法frm static。

Here is a nice code piece to illustrate what it means: 这是一个很好的代码段,以说明其含义:

class MyClass{

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

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

}

To call a non-static method, you need an instance (object) - because these methods belong to an instance, and in general only make sense in the context of an instance. 要调用非静态方法,您需要一个实例(对象)-因为这些方法属于实例,并且通常仅在实例的上下文中才有意义。

Static methods don't belong to an instance - they belong to the class. 静态方法不属于实例-它们属于类。 So there is no need to create an instance first, you can just call MyClass.doSomething() 因此,无需先创建实例,只需调用MyClass.doSomething()

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

But you can call a non-static method from a static method provided you first create an instance . 但是,只要您首先创建一个实例,就可以从静态方法中调用非静态方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM