Java 初始化
阿新 • • 發佈:2018-12-07
static 初始化
static 成員初始化順序
package object;
class Bowl {
Bowl(int marker)
{
System.out.printf("Bowl("+marker+")\n");
}
void f1(int marker)
{
System.out.printf("f1("+marker+")\n"); } } class Table{ static Bowl bowl1 =new Bowl(1); Table() { System.out.println("table()"); } void f2(int marker) { System.out.println("f2("+marker+")"); } static Bowl bowl2 = new Bowl(2); } class Cupboard { Bowl bowl3 = new Bowl(3); static Bowl bowl4 = new Bowl(4); Cupboard() { System.out.print("Cupboard\n"); bowl4.f1(2); } void f3(int marker) { System.out.println("f3("+marker+")"); } static Bowl bowl5 = new Bowl(5); } public class StaticInitialization{ public static void main(String args[]) { System.out.println("Creating new Cupboard() in main"); new Cupboard(); //靜態成員只有在第一個Cupboard在建立時才會初始化,此後,靜態成員不會再次初始化 System.out.println("Creating new Cupboard() in main"); Cupboard cupboard = new Cupboard(); new Table().f2(1); new Cupboard().f3(1); } }/* output: Creating new Cupboard() in main Bowl(4) Bowl(5) Bowl(3) Cupboard f1(2) Creating new Cupboard() in main Bowl(3) Cupboard f1(2) Bowl(1) Bowl(2) table() f2(1) Bowl(3) Cupboard f1(2) f3(1) *///~
顯示的初始化靜態方法
package object;
//: initialization/ExplicitStatic.java
import static net.mindview.util.Print.*;
class Cup
{
Cup(int marker)
{
print("Cup("+ marker +")");
}
void f(int marker) { print("f("+marker+")"); } } class Cups { static Cup cup1; static Cup cup2; //靜態域 static{ cup1 = new Cup(1); cup2 = new Cup(2); } //靜態塊 Cups() { print("Cups()"); } } public class ExplicitStatic{ public static void main(String args[]) { print("Inside main()"); Cups.cup1.f(99); // (1) 無論時通過(1)還是註釋掉(1)執行(2),Cups的靜態初始化都會執行
// 靜態初始化只會執行一次,如果(1)(2)全部註釋掉則不會執行初始化
} //static Cups cups1 = new Cups(); //(2) //static Cups cups2 = new Cups(); //(2) }/* output: Inside main() Cup(1) Cup(2) f(99) *///~
非靜態例項的初始化
package object; import static net.mindview.util.Print.*; class Mug { Mug(int marker) { print("mug("+ marker + ")"); } void f( int marker) { print("f("+marker +")"); } } public class Mugs{ Mug mug1; Mug mug2; { mug1= new Mug(1); mug2 = new Mug(2); print("mug1 & mug2 initialized"); } //例項初始化子句是再構造器之前執行的 Mugs() { print("MUgs()"); } Mugs(int i){ print("Mugs(int)"); } public static void main(String args[]) { print("Instde main()"); new Mugs(); print("new Musg() cmopleted"); new Mugs(1); print("new Mugs(1) completed"); } }/* output: Instde main() mug(1) mug(2) mug1 & mug2 initialized MUgs() new Musg() cmopleted mug(1) mug(2) mug1 & mug2 initialized Mugs(int) new Mugs(1) completed *///~
陣列的初始化
package object; import static net.mindview.util.Print.*; import java.util.*; public class ArrayNew{ public static void main(String args[]){ int [] a; Random rand = new Random(47); a = new int[rand.nextInt(20)]; print("length of a = " + a.length); print(Arrays.toString(a)); //Arrays.toString 產生一維陣列的列印版本 } }/* output: length of a = 18 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]//陣列元素會自動初始化為空值(對於數字和字元就是0,對於boolean是false) *///~