Announcement

Collapse
No announcement yet.

Ý nghĩa việc dụng một khối lệnh được đánh dấu là static ?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • [Java] Ý nghĩa việc dụng một khối lệnh được đánh dấu là static ?

    Mình có một class được định nghĩa như sau :
    Code:
    public class test {
        public test(){
            System.out.println("This is class test constructor");
        }
        static
        {
            System.out.println("static block 1");
        }
        {
            System.out.println("non-static block 1");
        }
        static
        {
            System.out.println("static block 2");
        }
        {
            System.out.println("non-static block 2");
        }
        
    }
    Sử dụng class test trên :

    Code:
    test t = new test();
    Và kết quả là :
    Code:
    static block 1
    static block 2
    non-static block 1
    non-static block 2
    This is class test constructor
    Mình không rõ ý nghĩa của việc đặc các khối lệnh đánh dấu bằng static và các khối lệnh khác như trên ? Xin giúp đỡ , nếu có thể , làm ơn cho biết kĩ thuật như trên có tên gọi là gì ? và có thể tìm hiểu thêm ở đâu ạ ?

    Xin cảm ơn .
    Amat Victoria Curam.

    ------
    Ping me at me@toan.mobi

  • #2
    đã tìm thấy 1 bài nói về cái này : http://isagoksu.com/2009/development...static-blocks/
    Amat Victoria Curam.

    ------
    Ping me at me@toan.mobi

    Comment


    • #3
      To figure this out, remember these rules: ( Đây là 4 luật cần nắm khi gặp dạng toán này )
      ■ Init blocks execute in the order they appear.
      ■ Static init blocks run once, when the class is first loaded.
      ■ Instance init blocks run every time a class instance is created.
      ■ Instance init blocks run after the constructor's call to super().

      Example:
      class Init {
      Init(int x) { System.out.println("1-arg const"); }
      Init() { System.out.println("no-arg const"); }
      static { System.out.println("1st static init"); }
      { System.out.println("1st instance init"); }
      { System.out.println("2nd instance init"); }
      static { System.out.println("2nd static init"); }
      public static void main(String [] args) {
      new Init();
      new Init(7);
      }
      }
      With those rules in mind, the following output should make sense:
      1st static init
      2nd static init
      1st instance init
      2nd instance init
      no-arg const
      1st instance init
      2nd instance init
      1-arg const
      bán tỏi đen, dcom 3g giá rẻ, đồng hồ thông minh dz09 giá rẻ

      Comment


      • #4
        Nhớ 4 luật đó thôi là đủ rồi
        bán tỏi đen, dcom 3g giá rẻ, đồng hồ thông minh dz09 giá rẻ

        Comment

        LHQC

        Collapse
        Working...
        X