Hỏi về Thứ tự chạy câu lệnh trong Singleton pattern

  • cho class:

public class Menu {
1 . . . .private static final Menu mn = new Menu();
2 . . . .private final String name = “Name Menu”;
3 . . . .private Menu() {}
4 . . . .public static Menu getMn() {
5 . . . . . . . .return mn;
6 . . . .}
7 . . . .public String getName() {
8 . . . . . . . .return name;
9 . . . .}
}


Menu p=Menu.getMn(); --> em cần chạy câu lệnh này .Ai có thể giải thích giúp em thứ tự chạy lệnh trong class Menu được không

1 Like

Chạy từ trên xuống dưới từ trái qua phải đó bạn.

1 Like

The sequence of events when a new object is instantiated via the new operator (known as the instantiation process) is as follows:

JVM allocates memory for the instance in the help.
JVM initializes the instance variables to their assigned values or default values.
JVM invokes the constructor.
The first statement of the constructor is always a call to its immediate superclass’ constructor. JVM invokes the selected superclass’ constructor.
JVM executes the instance initializers in the order of appearance.
JVM executes the body of the constructor.
The new operator returns a reference to the new object.
For example,:

public class Hello {
   private int number1 = 11;  // explicit initializer
   {                          // instance initializer
      number1 = 99;
      number2 = 88;
   }
   private int number2 = 22;  // explicit initializer
 
   public Hello() { }
 
   public Hello(int number1, int number2) { // Constructor
      this.number1 = number1;               // Run after initializers
      this.number2 = number2;
   }
 
   public static void main(String[] args) {
      Hello h = new Hello();
      System.out.println("number1 is " + h.number1);  // 99
      System.out.println("number2 is " + h.number2);  // 22
 
      Hello h2 = new Hello(55, 66);
      System.out.println("number1 is " + h2.number1);  // 55
      System.out.println("number2 is " + h2.number2);  // 66
   }
}

2 Likes

Ý mình là khi gọi hàm getMn() à bạn

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?