12 April 2017

Java Core: Block Code vs Static Block Code trong Java

Main.java
Java Core 2017
package demoblockcode;

public class Main {

    public static void main(String[] args) {
        // Case 1
        try {
            Class.forName("demoblockcode.a");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // Case 2
        // a a = new a();
        // Thi se chay block code Block code giong nhu 1 constructor
        // new a();
    }
}

class a {

    {
        // Block code
        System.out.println("Hello");
    }

    static {
        // Static block code
        System.out.println("Hallo");
    }
}
Main.java
Java Core 2017
package demoblockcode;

public class Main {

    public static void main(String[] args) {
 // Case 1
//  try {
//   Class.forName("demoblockcode.a");
//  } catch (ClassNotFoundException e) {
//   e.printStackTrace();
//  }
        // Case 2
        a a = new a();
 // Thi se chay block code Block code giong nhu 1 constructor
        // new a();
    }
}

class a {

    {
        // Block code
        System.out.println("Hello");
    }

    static {
        // Static block code
        System.out.println("Hallo");
    }
}
Main.java
Java Core 2017
package demoblockcode;

public class Main {

    public static void main(String[] args) {
        // Case 1
        //try {
        //        Class.forName("demoblockcode.a");
        //} catch (ClassNotFoundException e) {
        //        e.printStackTrace();
        //}
        // Case 2
        //a a = new a();
 // thi se chay block code Block code giong nhu 1 constructor Case 3
         new a();
    }
}

class a {

    {
        // Block code
        System.out.println("Hello");
    }

    static {
        // Static block code
        System.out.println("Hallo");
    }
}
Main.java
Java Core 2017
package demoblockcode;

public class Main {

    public static void main(String[] args) {

        {
            System.out.println("Hello");
        }
    }

    static {
        System.out.println("Hallo");
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang