简体   繁体   中英

Method is called automatically on object creation?

I can't understand the output of this code.

The class;

public class StaticMethodClass {

  public String str = display();

  public static String display() {
    System.out.println("Static Method");
    return "Hello";
  }

}

The main;

public static void main(String[] args) {
    System.out.println("Main");
    StaticMethodClass methodClass = new StaticMethodClass();
    System.out.println(methodClass.str);
  }

Output;

Main
Static Method
Hello

Why is display() method called automatically?

When you create an instance of the class it will need to initialize all the fields. Hence, the display() method is called to initialize "str" .

因为,您在类的实例处调用了display方法。

public String str = display();

创建新的StaticMethodClass时,它将通过调用display()初始化str。

Because class member str is initialized with this method upon creation of object of class StaticMethodClass . You create an object in the main() method.

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