[Think in Java Notes] Initialization of Static Data

xiaoxiao2021-03-06  14

An example in :

-------------------------------------------------- ----------------

// from 'Thinking in Java, 2nd Ed.' By Bruce Eckel // www.bruceeckel.com. See Copyright NOTICE IN COPYRIGHT.TXT./Specifying Initial Values ​​In A // Class Definition.

Class bowl {

Bowl (Int Marker) {System.out.println ("Bowl (" MARKER ")");} void f (int marker) {system.out.println ("f (" marker ")"); }

Class table {static bowl b1 = new bowl (1); table () {system.out.println ("Table ()"); b2.f (1);} void f2 (int marker) {system.out.println ("F2 (" MARKER ")") ")");} static bowl b2 = new bowl (2);}

Class Cupboard {Bowl B3 = New Bowl (3); Static Bowl B4 = New Bowl (4); Cupboard () {System.out.Println ("Cupboard ()"); b4.f (2);} void F3 Int marker {system.out.println ("F3 (" marker ")") ")") ")");} static bowl b5 = new bowl (5);}

Public class staticinitialization {public static void main (String [] args) {system.out.println ("Creating new cupboard () in main"); new cupboard (); System.out.Println ("CREATING New Cupboard () in "); new cupboard (); t2.f2 (1); t3.f3 (1);} static table t2 = new table (); static cupboard t3 = new cupboard ();

operation result:

-------------------------------------------------- ----------------

Bowl (1) Bowl (2) table () f (1) Bowl (4) Bowl (5) Bowl (3) Cupboard () F (2) Creating New Cupboard () in Mainbowl (3) Cupboard () f (2) Creating new cupboard () in mainbowl (3) Cupboard () f (2) F2 (1) F3 (1)

This is known:

1. If the Static object is not initialized, the initial Static object is initially, and then the Non-Static object;

2.Static object will only be initialized when loading is first loaded, and will not be initially;

转载请注明原文地址:https://www.9cbs.com/read-48862.html

New Post(0)