Java Initialization Order

Source: Internet
Author: User

1. Within the class, the order in which the variables are defined determines the order in which they are initialized, even if the variable definitions are scattered among the method definitions, they will be initialized before any method (including the constructor) is called.

2. Initialization of static data

Class Bowl{bowl (int marker) {print ("Bowl (" +marker+ ")");} void F1 (int marker) {print ("F1 (" +marker+ ")");} Class Table{static Bowl bowl1=new Bowl (1); Table () {Print ("table ()"); Bowl2.f1 (1);} void F2 (int marker) {print ("F2 (" +marker+ ")");} Static Bowl bowl2=new Bowl (2);}} Class Cupboard{bowl Bowl3=new Bowl (3); static Bowl bowl4=new Bowl (4); Cupboard () {print ("cupboard ()"); Bowl4.f1 (2);} void F3 (int marker) {print ("F3 (" +marker+ ")");} Static Bowl bowl5=new Bowl (5);} public class Staticinitialization{public static void Main (String args[]) {print ("Creating new Cupboard () in main"); new Cup Board ();p rint ("Creating New Cupboard () in main"); new cupboard (); Table.f2 (1); cupboard.f3 (1);} Static table Table=new table (), Static cupboard cupboard=new cupboard ();

Output

Bowl (1)

Bowl (2)

Table ()

F1 (1)

Bowl (4)

Bowl (5)

Bowl (3)

Cupboard ()

F1 (2)

Creating New Cupboard () in main

Bowl (3)

Cupboard ()

F1 (2)

Creating New Cupboard () in main

Bowl (3)

Cupboard ()

F1 (2)

F2 (1)

F3 (1)


3. Explicit static initialization

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 Exlicitstatic{public static void Main (String args[]) {print ("Inside main ()"); CUPS.CUP1.F (in);   (1)}//static cups cup1=new Cup ();  (2)//static cups cup2=new Cup ();  (2)}}

Output

Cup (1)

Cup (2)

F (99)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.