简体   繁体   English

在没有引用变量的情况下调用静态方法

[英]Calling static method without a reference variable

Why don't you need a reference variable in "method1( );" 为什么在“ method1();”中不需要引用变量? in order to call a static method from main? 为了从main调用静态方法?

public class MainClass { 
  public static void method1() { 
    System.out.println("Method1"); 
  }
  public static void main(String[ ] args) { 
    method1(); 
  } 
}

Without instantiating an Object variable like this for non static methods: 在不为非静态方法实例化Object变量的情况下:

MainClass var = new MainClass();
var.method1();

Static members ( Method, Field) does NOT belong to any object instances. 静态成员(方法,字段)不属于任何对象实例。 Static members exists Even there is NO object instance created. 静态成员存在即使没有创建对象实例。 Static members SHARED for all object instances. 静态成员共享所有对象实例。 That is why when you access static members, you DON'T have to use any object instances. 这就是为什么当您访问静态成员时,您不必使用任何对象实例。

For your case: 对于您的情况:

var1.method1() = var2.method1() = var3.method1() = MainClass.method1()

Because they are calling the same static member instance. 因为他们正在调用相同的静态成员实例。 BUT you are recommended that static members should be accessed in static way. 但是建议您以静态方式访问静态成员。

static members are class member not specific to object so we don't need of object. static members是不是特定于对象的class member ,因此我们不需要对象。 the best example is public static void main(String [] args) method itself. 最好的例子是public static void main(String [] args)方法本身。

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

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