简体   繁体   中英

Calling static method without a reference variable

Why don't you need a reference variable in "method1( );" in order to call a static method from 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:

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. the best example is public static void main(String [] args) method itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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