java-构造器的初始化

xiaoxiao2021-02-28  16

在类的内部,变量定义的先后顺序决定了初始化的顺序,并且都在任何方法(包括构造方法)前初始化
class Window{ public Window(int marker){ System.out.println("Window(" + marker + ")"); } } class House{ Window w1 = new Window(1); public House(){ System.out.println("House()"); w3 = new Window(33); } Window w2 = new Window(2); void f(){ System.out.print("f()"); } Window w3 = new Window(3); } public class Main { public static void main(String[] args) throws InterruptedException { House h = new House(); h.f(); } }

运行结果:

如果类中有静态变量(static),那么静态数据会先与非静态变量,并且一个类的static变量在只会在第一次被初始化一次。如果没有对静态变量进行初始化,那么静态变量采用基本类型的标准初值,如果是对象引用,则为null
class Bowl{ Bowl(int marker){ System.out.println("Bowl(" + marker + ")"); } void f1(int marker){ System.out.println("f1(" + marker + ")"); } } class table{ static Bowl bowl1= new Bowl(1); public table(){ System.out.println("table()"); bowl2.f1(1); } 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.println("cupboard"); bowl4.f1(2); } void f3(int marker){ System.out.println("f3(" + marker + ")"); } static Bowl bowl5 = new Bowl(5); } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Creating new cupboard() in main"); new cupboard(); System.out.println("Creating new cupboard() in main"); new cupboard(); t.f2(1); c.f3(1); } static table t = new table(); static cupboard c = new cupboard(); }

运行结果:

  对于静态变量,可以通过类直接调用。因此,当从未生成类的对象,类直接调用静态变量,则该类的静态变量都会被初始化
class cup{ cup(int marker){ System.out.println("cup(" + marker + ")"); } public void f(int marker){ System.out.println("f(" + marker + ")"); } } class cups{ static cup c1; static cup c2; static { c1 = new cup(1); c2 = new cup(2); } cups(){ System.out.println("cups()"); } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Inside main()"); cups.c1.f(99); } }

运行结果:

对于非静态块,每次创建对象,都会被初始化
class mug{ mug(int marker){ System.out.println("mug(" + marker + ")"); } public void f(int marker){ System.out.println("f(" + marker + ")"); } } class mugs{ mug mug1; mug mug2; { mug1 = new mug(1); mug2 = new mug(2); System.out.println("mug1 & mug2 finish"); } mugs(){ System.out.println("mugs()"); } mugs(int i){ System.out.println("mugs(int)"); } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Inside main"); new mugs(); System.out.println("new mugs() completed"); new mugs(1); System.out.println("new mugs(1) completed"); } }

结论:

       1) 对于类中变量的初始化,执行顺序:静态变量>非静态变量>构造方法

        2)即使当类没有定义对象时,通过类去调用静态变量,静态变量都会被初始化

        3)静态变量为类变量,只会被初始化一次

转载请注明原文地址: https://www.6miu.com/read-2450333.html

最新回复(0)